import { configureStore } from '@reduxjs/toolkit';
import GradeAllowancesSlice, {
  fetchGradeAllowances,
  createGradeAllowance,
  updateGradeAllowance,
  deleteGradeAllowance,
  clearGradeAllowances,
} from '../GradeAllowancesSlice';

jest.mock('@/services/api/api', () => ({
  apiGet: jest.fn(),
  apiPost: jest.fn(),
  apiPut: jest.fn(),
  apiDelete: jest.fn(),
}));

jest.mock('antd', () => ({
  message: { success: jest.fn(), error: jest.fn(), warning: jest.fn() },
}));

jest.mock('@/utilities/Helpers', () => {
  const mockHelpers = { handleServerError: jest.fn((e: any) => e?.message || 'Error') };
  return { __esModule: true, default: mockHelpers };
});

const { apiGet, apiPost, apiPut, apiDelete } = require('@/services/api/api');

const createTestStore = () =>
  configureStore({ reducer: { gradeAllowances: GradeAllowancesSlice.reducer } });

const mockAllowance = { id: '1', name: 'Housing', amount: 500, salary_grade_id: 'g1' };

describe('GradeAllowancesSlice', () => {
  beforeEach(() => jest.clearAllMocks());

  it('has correct initial state', () => {
    const store = createTestStore();
    const state = store.getState().gradeAllowances;
    expect(state.gradeAllowances).toEqual([]);
    expect(state.loading).toBe(false);
    expect(state.error).toBeNull();
  });

  describe('fetchGradeAllowances', () => {
    it('populates allowances on fulfilled', async () => {
      apiGet.mockResolvedValue({ data: [mockAllowance] });
      const store = createTestStore();
      await store.dispatch(fetchGradeAllowances());
      expect(store.getState().gradeAllowances.gradeAllowances).toEqual([mockAllowance]);
      expect(store.getState().gradeAllowances.loading).toBe(false);
    });

    it('passes filter params to API call', async () => {
      apiGet.mockResolvedValue({ data: [] });
      const store = createTestStore();
      await store.dispatch(fetchGradeAllowances({ salary_grade_id: 'g1', search: 'Housing' }));
      expect(apiGet).toHaveBeenCalledWith(
        expect.stringContaining('salary_grade_id=g1'),
      );
      expect(apiGet).toHaveBeenCalledWith(
        expect.stringContaining('search=Housing'),
      );
    });
  });

  describe('createGradeAllowance', () => {
    it('appends allowance on fulfilled', async () => {
      apiPost.mockResolvedValue({ data: { data: mockAllowance } });
      const store = createTestStore();
      await store.dispatch(createGradeAllowance({ name: 'Housing' } as any));
      expect(store.getState().gradeAllowances.gradeAllowances).toHaveLength(1);
      expect(store.getState().gradeAllowances.gradeAllowances[0]).toEqual(mockAllowance);
      expect(store.getState().gradeAllowances.loading).toBe(false);
    });
  });

  describe('updateGradeAllowance', () => {
    it('updates allowance in list on fulfilled', async () => {
      const updated = { ...mockAllowance, amount: 700 };
      apiPut.mockResolvedValue({ data: { data: updated } });
      const store = createTestStore();
      store.dispatch({ type: fetchGradeAllowances.fulfilled.type, payload: [mockAllowance] });
      await store.dispatch(updateGradeAllowance({ id: '1', amount: 700 } as any));
      expect(store.getState().gradeAllowances.gradeAllowances[0].amount).toBe(700);
      expect(store.getState().gradeAllowances.loading).toBe(false);
    });
  });

  describe('deleteGradeAllowance', () => {
    it('removes allowance from list on fulfilled', async () => {
      apiDelete.mockResolvedValue({});
      const store = createTestStore();
      store.dispatch({ type: fetchGradeAllowances.fulfilled.type, payload: [mockAllowance] });
      await store.dispatch(deleteGradeAllowance('1'));
      expect(store.getState().gradeAllowances.gradeAllowances).toEqual([]);
      expect(store.getState().gradeAllowances.loading).toBe(false);
    });
  });

  describe('clearGradeAllowances', () => {
    it('clears the allowances array', () => {
      const store = createTestStore();
      store.dispatch({ type: fetchGradeAllowances.fulfilled.type, payload: [mockAllowance] });
      store.dispatch(clearGradeAllowances());
      expect(store.getState().gradeAllowances.gradeAllowances).toEqual([]);
    });
  });
});
