import { configureStore } from '@reduxjs/toolkit';
import EmployeeAttendanceSlice, { fetchMyAttendance, fetchMyShifts } from '../EmployeeAttendanceSlice';

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

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

const createStore = () => configureStore({ reducer: { empAttendance: EmployeeAttendanceSlice.reducer } });

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

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

    it('populates attendance on fulfilled with paginated data', () => {
      const store = createStore();
      const meta = { current_page: 1, last_page: 1, per_page: 15, total: 2 };
      const payload = { data: [{ id: 'a1' }, { id: 'a2' }], meta };
      store.dispatch({ type: fetchMyAttendance.fulfilled.type, payload });
      expect(store.getState().empAttendance.attendance).toEqual(payload.data);
      expect(store.getState().empAttendance.attendanceMeta).toEqual(meta);
      expect(store.getState().empAttendance.loading).toBe(false);
    });

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

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

    it('populates shifts on fulfilled', () => {
      const store = createStore();
      const payload = { data: [{ id: 's1' }] };
      store.dispatch({ type: fetchMyShifts.fulfilled.type, payload });
      expect(store.getState().empAttendance.shifts).toEqual(payload.data);
      expect(store.getState().empAttendance.loading).toBe(false);
    });
  });
});
