import {getBandeau} from './bandeauService';
import http from '@/http';

const mockedHttp = http as jest.Mocked<typeof http>;

const BANDEAU_PATH = '/socle_bandeaux';
const IMAGE_PATH = '/media/socle_bandeaux/1/MediaPrincipal';

function collection(bandeau: Record<string, unknown>) {
  return {status: 200, data: {'hydra:member': [bandeau]}};
}

const activeBandeau = {
  banId: 1,
  banActif: true,
  banToutesPages: false,
  imageUrl: IMAGE_PATH,
};

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

  it('shouldReturnNullWhenBandeauIsInactive', async () => {
    mockedHttp.get.mockResolvedValue(collection({...activeBandeau, banActif: false}));

    expect(await getBandeau()).toBeNull();
    expect(mockedHttp.get).toHaveBeenCalledTimes(1);
    expect(mockedHttp.get).toHaveBeenCalledWith(BANDEAU_PATH);
  });

  it('shouldReturnNullWhenNoImageHasBeenUploaded', async () => {
    mockedHttp.get
      .mockResolvedValueOnce(collection(activeBandeau))
      .mockResolvedValueOnce({
        status: 200,
        data: {url: 'https://dummyimage.com/600x400/f60/fff&text=Votre+image+ici...'},
      });

    expect(await getBandeau()).toBeNull();
    expect(mockedHttp.get).toHaveBeenLastCalledWith(IMAGE_PATH);
  });

  it('shouldReturnTheResolvedImageOfAnActiveBandeau', async () => {
    mockedHttp.get
      .mockResolvedValueOnce(collection({...activeBandeau, banToutesPages: true}))
      .mockResolvedValueOnce({
        status: 200,
        data: {url: 'https://media.tamm-kreiz.bzh/bandeau.jpg'},
      });

    expect(await getBandeau()).toEqual({
      imageUrl: 'https://media.tamm-kreiz.bzh/bandeau.jpg',
      toutesPages: true,
      lien: null,
    });
  });

  it('shouldReturnNullWhenTheApiFails', async () => {
    mockedHttp.get.mockRejectedValue(new Error('Network error'));

    expect(await getBandeau()).toBeNull();
  });

  it('shouldCarryTheLinkOfTheBandeau', async () => {
    mockedHttp.get
      .mockResolvedValueOnce(collection({...activeBandeau, banLien: 'https://www.tamm-kreiz.bzh/festival'}))
      .mockResolvedValueOnce({status: 200, data: {url: 'https://pimcore.test/bandeau.jpg'}});

    expect(await getBandeau()).toEqual({imageUrl: 'https://pimcore.test/bandeau.jpg', toutesPages: false, lien: 'https://www.tamm-kreiz.bzh/festival'});
  });

  it('shouldHaveNoLinkWhenNoneIsConfigured', async () => {
    mockedHttp.get
      .mockResolvedValueOnce(collection(activeBandeau))
      .mockResolvedValueOnce({status: 200, data: {url: 'https://pimcore.test/bandeau.jpg'}});

    expect((await getBandeau())?.lien).toBeNull();
  });
});
