import { configureStore } from '@reduxjs/toolkit';
import EmployeePayrollSlice, { fetchMyPayslips, fetchMySalarySummary, fetchMyLoans } from '../EmployeePayrollSlice';

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 createStore = () => configureStore({ reducer: { empPayroll: EmployeePayrollSlice.reducer } });

describe('EmployeePayrollSlice', () => {
  it('has correct initial state', () => {
    const store = createStore();
    const state = store.getState().empPayroll;
    expect(state.payslips).toEqual([]);
    expect(state.payslipsMeta).toBeNull();
    expect(state.salarySummary).toBeNull();
    expect(state.loans).toEqual([]);
    expect(state.loading).toBe(false);
    expect(state.error).toBeNull();
  });

  describe('fetchMyPayslips', () => {
    it('sets loading on pending', () => {
      const store = createStore();
      store.dispatch({ type: fetchMyPayslips.pending.type });
      expect(store.getState().empPayroll.loading).toBe(true);
    });

    it('populates payslips on fulfilled', () => {
      const store = createStore();
      const meta = { current_page: 1, last_page: 1, per_page: 15, total: 1 };
      const payload = { data: [{ id: 'ps1', net_salary: '1000' }], meta };
      store.dispatch({ type: fetchMyPayslips.fulfilled.type, payload });
      expect(store.getState().empPayroll.payslips).toEqual(payload.data);
      expect(store.getState().empPayroll.payslipsMeta).toEqual(meta);
      expect(store.getState().empPayroll.loading).toBe(false);
    });

    it('sets loading false on rejected', () => {
      const store = createStore();
      store.dispatch({ type: fetchMyPayslips.pending.type });
      store.dispatch({ type: fetchMyPayslips.rejected.type, payload: { message: 'Server error' } });
      expect(store.getState().empPayroll.loading).toBe(false);
    });
  });

  describe('fetchMySalarySummary', () => {
    it('sets salarySummary on fulfilled', () => {
      const store = createStore();
      const summary = { grade_assignment: null, allowances: [], deductions: [], latest_payslip: null };
      store.dispatch({ type: fetchMySalarySummary.fulfilled.type, payload: summary });
      expect(store.getState().empPayroll.salarySummary).toEqual(summary);
    });
  });

  describe('fetchMyLoans', () => {
    it('populates loans on fulfilled', () => {
      const store = createStore();
      const loans = [{ id: 'l1', status: 'active' }];
      store.dispatch({ type: fetchMyLoans.fulfilled.type, payload: loans });
      expect(store.getState().empPayroll.loans).toEqual(loans);
    });
  });
});
