import http from '@/http';
import {getMediaPrincipalUrl} from '@/services/mediaService';
import {entreeHref, type EntreeCible} from '@/utils/entreeHref';
import type {AnimateurAvecPhoto} from '@/components/shared/AnimateursGallery/AnimateursGallery';

/** Entrée liée (structure parente ou rattachée) telle que l'API la sérialise dans une fiche. */
export interface EntreeLiee extends EntreeCible {
  aenId: number;
  aenLibelle: string;
}

export interface FederationLiee {
  fedId: number;
  /** Entrée annuaire de la fédération : porte son logo et sa fiche. */
  fedAenId: number | null;
  fedLibelle: string | null;
}

export interface EntreeRelations {
  meres: EntreeLiee[];
  filles: EntreeLiee[];
  federations: FederationLiee[];
}

const VIDE: EntreeRelations = {meres: [], filles: [], federations: []};

/**
 * Parents, enfants et fédérations d'une entrée annuaire (fiches groupe et ensemble). Sans API, des listes vides :
 * les blocs « voir aussi » et « fédérations » restent optionnels.
 */
export async function getEntreeRelations(aenId: number | string): Promise<EntreeRelations> {
  try {
    const response = await http.get(`/annuaire_entrees/${aenId}`);
    const data = response.data ?? {};
    return {
      meres: data.meres ?? [],
      filles: data.filles ?? [],
      federations: (data.federations ?? []).map((f: {fedId: number; fedAenId?: number | null; fedLibelle?: string | null}) => ({
        fedId: f.fedId,
        fedAenId: f.fedAenId ?? null,
        fedLibelle: f.fedLibelle ?? null,
      })),
    };
  } catch {
    return VIDE;
  }
}

/** Galerie « voir aussi » : nom, média principal et fiche publique de chaque entrée liée. */
export async function galerieEntrees(locale: string, entrees: EntreeLiee[]): Promise<AnimateurAvecPhoto[]> {
  return Promise.all(
    entrees.map(async (entree) => ({
      aenId: entree.aenId,
      aenLibelle: entree.aenLibelle,
      photoUrl: await getMediaPrincipalUrl('annuaire_entree', entree.aenId, 'v6_annuaire_cover_4_3'),
      href: entreeHref(locale, entree),
    }))
  );
}
