import http from '@/http';
import {galerieEntrees, getEntreeRelations} from './entreeRelationsService';

jest.mock('@/services/mediaService', () => ({
  getMediaPrincipalUrl: jest.fn((_t: string, id: number) => Promise.resolve(id === 5 ? 'https://media.test/5.jpg' : null)),
}));

const mockGet = http.get as jest.Mock;

describe('entreeRelationsService', () => {
  beforeEach(() => {
    jest.clearAllMocks();
  });

  it('shouldReadParentsChildrenAndFederationsOfAnEntry', async () => {
    mockGet.mockResolvedValue({data: {
      aenId: 42,
      meres: [{aenId: 5, aenLibelle: 'Kevrenn', aenMorale: 1, aenFmu: [{fmuId: 9}]}],
      filles: [],
      federations: [{fedId: 3, fedAenId: 77, fedLibelle: 'Kendalc\'h', fedIconeMembres: 1}],
    }});

    const relations = await getEntreeRelations(42);

    expect(mockGet).toHaveBeenCalledWith('/annuaire_entrees/42');
    expect(relations.meres).toHaveLength(1);
    expect(relations.filles).toEqual([]);
    expect(relations.federations).toEqual([{fedId: 3, fedAenId: 77, fedLibelle: 'Kendalc\'h'}]);
  });

  it('shouldReturnEmptyRelationsWhenTheApiFails', async () => {
    mockGet.mockRejectedValue(new Error('réseau'));

    expect(await getEntreeRelations(42)).toEqual({meres: [], filles: [], federations: []});
  });

  it('shouldBuildAGalleryWithPhotoAndTheRightSheetForEachEntry', async () => {
    const galerie = await galerieEntrees('fr', [
      {aenId: 5, aenLibelle: 'Kevrenn', aenMorale: 1, aenFmu: [{fmuId: 9}]},
      {aenId: 6, aenLibelle: 'Anna Le Goff', aenMorale: 0},
    ]);

    expect(galerie).toEqual([
      {aenId: 5, aenLibelle: 'Kevrenn', photoUrl: 'https://media.test/5.jpg', href: '/fr/groupes/9'},
      {aenId: 6, aenLibelle: 'Anna Le Goff', photoUrl: null, href: '/fr/personne/6/anna-le-goff'},
    ]);
  });
});
