import React from 'react';
import {render, screen, waitFor} from '@testing-library/react';

jest.mock('next/navigation', () => ({useRouter: () => ({push: jest.fn()})}));
jest.mock('next-intl', () => ({useTranslations: () => (key: string) => key}));

import EventGroupeSection from '../EventGroupeSection';
import http from '@/http';

const evenement = (eveId: number, eveDate: string, vilNom: string) => ({eveId, eveDate, eveTev: {tevLibelle: 'Fest-noz'}, eveVil: {vilNom, vilCodepostal: '35000'}});

describe('EventGroupeSection — programmé ou organisateur', () => {
  beforeEach(() => {
    jest.clearAllMocks();
  });

  it('shouldMergeTheEventsWhereTheEntryOrganisesWithThoseWhereItPlays', async () => {
    (http.get as jest.Mock).mockImplementation((url: string) =>
      url.includes('aenOrganisateurs=')
        ? Promise.resolve({data: {'hydra:member': [evenement(2, '2030-04-01', 'Vannes'), evenement(1, '2030-05-02', 'Rennes')]}})
        : Promise.resolve({data: {'hydra:member': [evenement(1, '2030-05-02', 'Rennes')]}})
    );

    render(<EventGroupeSection aenId={42} aenLibelle="Cercle" locale="fr" avecOrganisateur />);

    await waitFor(() => expect(http.get).toHaveBeenCalledTimes(2));
    expect(http.get).toHaveBeenCalledWith(expect.stringContaining('aenOrganisateurs=42'), expect.anything());
    const titres = await screen.findAllByRole('heading', {level: 4});
    expect(titres.map(t => t.textContent)).toEqual(['Fest-noz à Vannes', 'Fest-noz à Rennes']);
  });

  it('shouldOnlyAskForTheEventsWhereItPlaysByDefault', async () => {
    (http.get as jest.Mock).mockResolvedValue({data: {'hydra:member': []}});

    render(<EventGroupeSection aenId={42} aenLibelle="Cercle" locale="fr" />);

    await waitFor(() => expect(http.get).toHaveBeenCalledTimes(1));
    expect(http.get).toHaveBeenCalledWith(expect.stringContaining('aenParticipants=42'), expect.anything());
  });
});
