import { configureStore } from '@reduxjs/toolkit';
import LeaveRequestsSlice, { fetchLeaveRequests, fetchMyLeaveRequests, fetchLeaveRequest } from '../LeaveRequestsSlice';

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: { leaveRequests: LeaveRequestsSlice.reducer } });

describe('LeaveRequestsSlice', () => {
  it('has correct initial state', () => {
    const state = createStore().getState().leaveRequests;
    expect(state.leaveRequests).toEqual([]);
    expect(state.myLeaveRequests).toEqual([]);
    expect(state.selectedLeaveRequest).toBeNull();
    expect(state.calculation).toBeNull();
    expect(state.loading).toBe(false);
    expect(state.actionLoading).toBe(false);
    expect(state.error).toBeNull();
  });

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

  it('populates data on fetchLeaveRequests.fulfilled', () => {
    const store = createStore();
    const data = [{ id: '1', status: 'pending' }] as any;
    store.dispatch(fetchLeaveRequests.fulfilled(data, 'req'));
    expect(store.getState().leaveRequests.leaveRequests).toEqual(data);
    expect(store.getState().leaveRequests.loading).toBe(false);
  });

  it('populates my leave requests on fetchMyLeaveRequests.fulfilled', () => {
    const store = createStore();
    const data = [{ id: '2', status: 'approved' }] as any;
    store.dispatch(fetchMyLeaveRequests.fulfilled(data, 'req'));
    expect(store.getState().leaveRequests.myLeaveRequests).toEqual(data);
  });

  it('sets actionLoading on fetchLeaveRequest.pending', () => {
    const store = createStore();
    store.dispatch(fetchLeaveRequest.pending('req', '1'));
    expect(store.getState().leaveRequests.actionLoading).toBe(true);
  });

  it('populates selected leave request on fetchLeaveRequest.fulfilled', () => {
    const store = createStore();
    const data = { id: '1', status: 'pending' } as any;
    store.dispatch(fetchLeaveRequest.fulfilled(data, 'req', '1'));
    expect(store.getState().leaveRequests.selectedLeaveRequest).toEqual(data);
    expect(store.getState().leaveRequests.actionLoading).toBe(false);
  });
});
