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 LiberatoriaService from './liberatoria.service';
import Liberatoria from './liberatoria.vue';

type LiberatoriaComponentType = InstanceType<typeof Liberatoria>;

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

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

  describe('Liberatoria Management Component', () => {
    let liberatoriaServiceStub: SinonStubbedInstance<LiberatoriaService>;
    let mountOptions: MountingOptions<LiberatoriaComponentType>['global'];

    beforeEach(() => {
      liberatoriaServiceStub = sinon.createStubInstance<LiberatoriaService>(LiberatoriaService);
      liberatoriaServiceStub.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,
          liberatoriaService: () => liberatoriaServiceStub,
        },
      };
    });

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

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

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

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

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

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

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

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

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