import { configureStore } from '@reduxjs/toolkit';
import { ApplicantsSlice, fetchApplicants, fetchApplicant, clearApplicant } from '../ApplicantsSlice';

jest.mock('@/services/api/api', () => ({ apiGet: jest.fn(), apiPost: jest.fn(), apiPut: jest.fn(), apiDelete: jest.fn(), apiDownloadBlob: jest.fn(), axiosInstance: { delete: jest.fn() }, API_ENDPOINT: '' }));
jest.mock('antd', () => ({ message: { success: jest.fn(), error: jest.fn(), warning: jest.fn() } }));
jest.mock('@/utilities/Helpers', () => ({ default: { handleServerError: jest.fn((e) => e?.message || 'Error') } }));

const createStore = () => configureStore({ reducer: { applicants: ApplicantsSlice.reducer } });

describe('ApplicantsSlice', () => {
  it('has correct initial state', () => {
    const state = createStore().getState().applicants;
    expect(state.applicants).toEqual([]);
    expect(state.applicant).toBeNull();
    expect(state.meta).toBeNull();
    expect(state.loading).toBe(false);
    expect(state.actionLoading).toBe(false);
    expect(state.error).toBeNull();
  });

  it('sets loading on fetchApplicants.pending', () => {
    const store = createStore();
    store.dispatch(fetchApplicants.pending('req'));
    expect(store.getState().applicants.loading).toBe(true);
  });

  it('populates data on fetchApplicants.fulfilled', () => {
    const store = createStore();
    const payload = { data: [{ id: '1', first_name: 'John' }], meta: { total: 1 } } as any;
    store.dispatch(fetchApplicants.fulfilled(payload, 'req'));
    expect(store.getState().applicants.applicants).toEqual(payload.data);
    expect(store.getState().applicants.meta).toEqual(payload.meta);
    expect(store.getState().applicants.loading).toBe(false);
  });

  it('populates single item on fetchApplicant.fulfilled', () => {
    const store = createStore();
    const payload = { data: { id: '1', first_name: 'John' } } as any;
    store.dispatch(fetchApplicant.fulfilled(payload, 'req', '1'));
    expect(store.getState().applicants.applicant).toEqual(payload.data);
    expect(store.getState().applicants.loading).toBe(false);
  });

  it('clears applicant on clearApplicant', () => {
    const store = createStore();
    store.dispatch(fetchApplicant.fulfilled({ data: { id: '1' } } as any, 'req', '1'));
    store.dispatch(clearApplicant());
    expect(store.getState().applicants.applicant).toBeNull();
  });
});
