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 UtenteAppService from './utente-app.service';
import UtenteApp from './utente-app.vue';

type UtenteAppComponentType = InstanceType<typeof UtenteApp>;

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

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

  describe('UtenteApp Management Component', () => {
    let utenteAppServiceStub: SinonStubbedInstance<UtenteAppService>;
    let mountOptions: MountingOptions<UtenteAppComponentType>['global'];

    beforeEach(() => {
      utenteAppServiceStub = sinon.createStubInstance<UtenteAppService>(UtenteAppService);
      utenteAppServiceStub.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,
          utenteAppService: () => utenteAppServiceStub,
        },
      };
    });

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

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

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

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

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

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

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

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

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