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

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

import AlertService from '@/shared/alert/alert.service';

import MessaggioDetails from './messaggio-details.vue';
import MessaggioService from './messaggio.service';

type MessaggioDetailsComponentType = InstanceType<typeof MessaggioDetails>;

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

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

const messaggioSample = { id: 123 };

describe('Component Tests', () => {
  let alertService: AlertService;

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

  describe('Messaggio Management Detail Component', () => {
    let messaggioServiceStub: SinonStubbedInstance<MessaggioService>;
    let mountOptions: MountingOptions<MessaggioDetailsComponentType>['global'];

    beforeEach(() => {
      route = {};
      messaggioServiceStub = sinon.createStubInstance<MessaggioService>(MessaggioService);

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

      mountOptions = {
        stubs: {
          'font-awesome-icon': true,
          'router-link': true,
        },
        provide: {
          alertService,
          messaggioService: () => messaggioServiceStub,
        },
      };
    });

    describe('Navigate to details', () => {
      it('Should call load all on init', async () => {
        // GIVEN
        messaggioServiceStub.find.resolves(messaggioSample);
        route = {
          params: {
            messaggioId: `${123}`,
          },
        };
        const wrapper = shallowMount(MessaggioDetails, { global: mountOptions });
        const comp = wrapper.vm;
        // WHEN
        await comp.$nextTick();

        // THEN
        expect(comp.messaggio).toMatchObject(messaggioSample);
      });
    });

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

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

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