import { generateFlagConfig } from "~/lib/flag-generator";
import {
  parseFlagConfig,
  type AvatarData,
  type FlagConfig,
  type RawFlagConfig,
} from "~/lib/flag-types";

interface UserAvatarSource {
  id: string;
  customAvatarUrl?: string | null;
  avatarType?: string | null;
  flagConfig?: RawFlagConfig | null;
}

interface TeamAvatarSource {
  id: string;
  logoUrl?: string | null;
  avatarType?: string | null;
  flagConfig?: RawFlagConfig | null;
}

export function getDisplayFlagConfig(id: string, flagConfig: RawFlagConfig | null | undefined): FlagConfig {
  return parseFlagConfig(flagConfig) ?? generateFlagConfig(id);
}

export function resolveUserAvatarData(user: UserAvatarSource): AvatarData {
  if (user.avatarType === "uploaded" && user.customAvatarUrl) {
    return { type: "image", url: user.customAvatarUrl };
  }

  return { type: "flag", config: getDisplayFlagConfig(user.id, user.flagConfig) };
}

export function resolveTeamAvatarData(
  team: TeamAvatarSource,
  ownerAvatarData?: AvatarData | null
): AvatarData {
  if (team.avatarType === "uploaded" && team.logoUrl) {
    return { type: "image", url: team.logoUrl };
  }

  if (team.avatarType === "flag") {
    return { type: "flag", config: getDisplayFlagConfig(team.id, team.flagConfig) };
  }

  return ownerAvatarData ?? { type: "flag", config: getDisplayFlagConfig(team.id, team.flagConfig) };
}
