import type { Country, CountryRow } from "@/lib/api/types/country.types";

export function mapCountryToRow(country: Country, index: number): CountryRow {
  return {
    sno:        index + 1,
    id:         country.id,
    name:       country.name     ?? "—",
    code:       country.code     ?? "—",
    flag_url:   country.flag_url ?? "",
    created_at: country.created_at,
    updated_at: country.updated_at,
  };
}

export function mapCountriesApiResponse(countries: Country[]): CountryRow[] {
  return countries.map((c, idx) => mapCountryToRow(c, idx));
}

export function mapColumnKeyToValue(key: string, row: CountryRow): any {
  const map: Record<string, any> = {
    name:     row.name,
    code:     row.code,
    flag_url: row.flag_url,
    flag:     row.flag_url,   // alias used by dynamic columns
    created_at: row.created_at
      ? new Date(row.created_at).toLocaleDateString("en-GB", { day: "2-digit", month: "short", year: "numeric" }).replace(/ /g, "-")
      : "—",
    updated_at: row.updated_at
      ? new Date(row.updated_at).toLocaleDateString("en-GB", { day: "2-digit", month: "short", year: "numeric" }).replace(/ /g, "-")
      : "—",
  };
  return map[key] ?? row[key] ?? "—";
}

export function formatCountryForExport(row: CountryRow): Record<string, string | number> {
  return {
    "No.":     row.sno,
    "Name":    row.name,
    "Code":    row.code,
    "Flag URL":row.flag_url,
    "Created": row.created_at ? new Date(row.created_at).toLocaleDateString("en-GB") : "",
  };
}
