import { vitest } from 'vitest';
import { type RouteLocation } from 'vue-router';

import { type MountingOptions, shallowMount } from '@vue/test-utils';
import dayjs from 'dayjs';
import sinon, { type SinonStubbedInstance } from 'sinon';

import ConfermaService from '@/entities/conferma/conferma.service';
import StrutturaService from '@/entities/struttura/struttura.service';
import UtenteAppService from '@/entities/utente-app/utente-app.service';
import AlertService from '@/shared/alert/alert.service';
import { DATE_TIME_LONG_FORMAT } from '@/shared/composables/date-format';

import PrenotazioneUpdate from './prenotazione-update.vue';
import PrenotazioneService from './prenotazione.service';

type PrenotazioneUpdateComponentType = InstanceType<typeof PrenotazioneUpdate>;

let route: Partial<RouteLocation>;
const routerGoMock = vitest.fn();

vitest.mock('vue-router', () => ({
  useRoute: () => route,
  useRouter: () => ({ go: routerGoMock }),
}));

const prenotazioneSample = { id: 123 };

describe('Component Tests', () => {
  let mountOptions: MountingOptions<PrenotazioneUpdateComponentType>['global'];
  let alertService: AlertService;

  describe('Prenotazione Management Update Component', () => {
    let comp: PrenotazioneUpdateComponentType;
    let prenotazioneServiceStub: SinonStubbedInstance<PrenotazioneService>;

    beforeEach(() => {
      route = {};
      prenotazioneServiceStub = sinon.createStubInstance<PrenotazioneService>(PrenotazioneService);
      prenotazioneServiceStub.retrieve.onFirstCall().resolves(Promise.resolve([]));

      alertService = new AlertService({
        i18n: { t: vitest.fn() } as any,
        toast: {
          show: vitest.fn(),
        } as any,
      });

      mountOptions = {
        stubs: {
          'font-awesome-icon': true,
          'b-input-group': true,
          'b-input-group-prepend': true,
          'b-form-datepicker': true,
          'b-form-input': true,
        },
        provide: {
          alertService,
          prenotazioneService: () => prenotazioneServiceStub,
          confermaService: () =>
            sinon.createStubInstance<ConfermaService>(ConfermaService, {
              retrieve: sinon.stub().resolves({}),
            } as any),
          utenteAppService: () =>
            sinon.createStubInstance<UtenteAppService>(UtenteAppService, {
              retrieve: sinon.stub().resolves({}),
            } as any),
          strutturaService: () =>
            sinon.createStubInstance<StrutturaService>(StrutturaService, {
              retrieve: sinon.stub().resolves({}),
            } as any),
        },
      };
    });

    afterEach(() => {
      vitest.resetAllMocks();
    });

    describe('load', () => {
      beforeEach(() => {
        const wrapper = shallowMount(PrenotazioneUpdate, { global: mountOptions });
        comp = wrapper.vm;
      });
      it('Should convert date from string', () => {
        // GIVEN
        const date = new Date('2019-10-15T11:42:02Z');

        // WHEN
        const convertedDate = comp.convertDateTimeFromServer(date);

        // THEN
        expect(convertedDate).toEqual(dayjs(date).format(DATE_TIME_LONG_FORMAT));
      });

      it('Should not convert date if date is not present', () => {
        expect(comp.convertDateTimeFromServer(null)).toBeNull();
      });
    });

    describe('save', () => {
      it('Should call update service on save for existing entity', async () => {
        // GIVEN
        const wrapper = shallowMount(PrenotazioneUpdate, { global: mountOptions });
        comp = wrapper.vm;
        comp.prenotazione = prenotazioneSample;
        prenotazioneServiceStub.update.resolves(prenotazioneSample);

        // WHEN
        comp.save();
        await comp.$nextTick();

        // THEN
        expect(prenotazioneServiceStub.update.calledWith(prenotazioneSample)).toBeTruthy();
        expect(comp.isSaving).toEqual(false);
      });

      it('Should call create service on save for new entity', async () => {
        // GIVEN
        const entity = {};
        prenotazioneServiceStub.create.resolves(entity);
        const wrapper = shallowMount(PrenotazioneUpdate, { global: mountOptions });
        comp = wrapper.vm;
        comp.prenotazione = entity;

        // WHEN
        comp.save();
        await comp.$nextTick();

        // THEN
        expect(prenotazioneServiceStub.create.calledWith(entity)).toBeTruthy();
        expect(comp.isSaving).toEqual(false);
      });
    });

    describe('Before route enter', () => {
      it('Should retrieve data', async () => {
        // GIVEN
        prenotazioneServiceStub.find.resolves(prenotazioneSample);
        prenotazioneServiceStub.retrieve.resolves([prenotazioneSample]);

        // WHEN
        route = {
          params: {
            prenotazioneId: `${prenotazioneSample.id}`,
          },
        };
        const wrapper = shallowMount(PrenotazioneUpdate, { global: mountOptions });
        comp = wrapper.vm;
        await comp.$nextTick();

        // THEN
        expect(comp.prenotazione).toMatchObject(prenotazioneSample);
      });
    });

    describe('Previous state', () => {
      it('Should go previous state', async () => {
        prenotazioneServiceStub.find.resolves(prenotazioneSample);
        const wrapper = shallowMount(PrenotazioneUpdate, { global: mountOptions });
        comp = wrapper.vm;
        await comp.$nextTick();

        comp.previousState();
        await comp.$nextTick();

        expect(routerGoMock).toHaveBeenCalledWith(-1);
      });
    });
  });
});
