import { configureStore } from '@reduxjs/toolkit';
import { EmployeeCategorySlice, fetchEmployeeCategories, createEmployeeCategory } from '../EmployeeCategorySlice';

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', () => ({
  default: { handleServerError: jest.fn((e) => e?.message || 'Error') },
}));

const createStore = () =>
  configureStore({ reducer: { employeeCategories: EmployeeCategorySlice.reducer } });

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

  it('sets loading to true on fetchEmployeeCategories.pending', () => {
    const store = createStore();
    store.dispatch(fetchEmployeeCategories.pending('requestId'));
    const state = store.getState().employeeCategories;
    expect(state.loading).toBe(true);
  });

  it('populates categories on fetchEmployeeCategories.fulfilled', () => {
    const store = createStore();
    const mockData = [{ id: '1', name: 'Senior Staff' }] as any;
    store.dispatch(fetchEmployeeCategories.fulfilled(mockData, 'requestId'));
    const state = store.getState().employeeCategories;
    expect(state.employeeCategories).toEqual(mockData);
    expect(state.loading).toBe(false);
  });

  it('prepends new category on createEmployeeCategory.fulfilled', () => {
    const store = createStore();
    const newCategory = { id: '2', name: 'Junior Staff' } as any;
    store.dispatch(createEmployeeCategory.fulfilled(newCategory, 'requestId', { name: 'Junior Staff' } as any));
    const state = store.getState().employeeCategories;
    expect(state.employeeCategories[0]).toEqual(newCategory);
    expect(state.loading).toBe(false);
  });
});
