import { vitest } from 'vitest';

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

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

import MessaggioService from './messaggio.service';
import Messaggio from './messaggio.vue';

type MessaggioComponentType = InstanceType<typeof Messaggio>;

const bModalStub = {
  render: () => {},
  methods: {
    hide: () => {},
    show: () => {},
  },
};

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

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

    beforeEach(() => {
      messaggioServiceStub = sinon.createStubInstance<MessaggioService>(MessaggioService);
      messaggioServiceStub.retrieve.resolves({ headers: {} });

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

      mountOptions = {
        stubs: {
          bModal: bModalStub as any,
          'font-awesome-icon': true,
          'b-badge': true,
          'b-button': true,
          'router-link': true,
        },
        directives: {
          'b-modal': {},
        },
        provide: {
          alertService,
          messaggioService: () => messaggioServiceStub,
        },
      };
    });

    describe('Mount', () => {
      it('Should call load all on init', async () => {
        // GIVEN
        messaggioServiceStub.retrieve.resolves({ headers: {}, data: [{ id: 123 }] });

        // WHEN
        const wrapper = shallowMount(Messaggio, { global: mountOptions });
        const comp = wrapper.vm;
        await comp.$nextTick();

        // THEN
        expect(messaggioServiceStub.retrieve.calledOnce).toBeTruthy();
        expect(comp.messaggios[0]).toEqual(expect.objectContaining({ id: 123 }));
      });
    });
    describe('Handles', () => {
      let comp: MessaggioComponentType;

      beforeEach(async () => {
        const wrapper = shallowMount(Messaggio, { global: mountOptions });
        comp = wrapper.vm;
        await comp.$nextTick();
        messaggioServiceStub.retrieve.reset();
        messaggioServiceStub.retrieve.resolves({ headers: {}, data: [] });
      });

      it('Should call delete service on confirmDelete', async () => {
        // GIVEN
        messaggioServiceStub.delete.resolves({});

        // WHEN
        comp.prepareRemove({ id: 123 });

        comp.removeMessaggio();
        await comp.$nextTick(); // clear components

        // THEN
        expect(messaggioServiceStub.delete.called).toBeTruthy();

        // THEN
        await comp.$nextTick(); // handle component clear watch
        expect(messaggioServiceStub.retrieve.callCount).toEqual(1);
      });
    });
  });
});
