import { configureStore } from '@reduxjs/toolkit';
import PipCheckInSlice, { clearPipCheckIns, fetchPipCheckIns, createPipCheckIn, updatePipCheckIn, deletePipCheckIn } from '../PipCheckInSlice';

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

const createStore = () => configureStore({ reducer: { pc: PipCheckInSlice.reducer } });

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

  it('populates on fetchPipCheckIns.fulfilled', () => {
    const store = createStore();
    store.dispatch({ type: fetchPipCheckIns.fulfilled.type, payload: [{ id: '1' }] });
    expect(store.getState().pc.pipCheckIns).toEqual([{ id: '1' }]);
  });

  it('appends on createPipCheckIn.fulfilled', () => {
    const store = createStore();
    store.dispatch({ type: createPipCheckIn.fulfilled.type, payload: { id: '1' } });
    expect(store.getState().pc.pipCheckIns).toHaveLength(1);
  });

  it('updates in place on updatePipCheckIn.fulfilled', () => {
    const store = createStore();
    store.dispatch({ type: fetchPipCheckIns.fulfilled.type, payload: [{ id: '1', note: 'old' }] });
    store.dispatch({ type: updatePipCheckIn.fulfilled.type, payload: { id: '1', note: 'new' } });
    expect(store.getState().pc.pipCheckIns[0].note).toBe('new');
  });

  it('removes on deletePipCheckIn.fulfilled', () => {
    const store = createStore();
    store.dispatch({ type: fetchPipCheckIns.fulfilled.type, payload: [{ id: '1' }] });
    store.dispatch({ type: deletePipCheckIn.fulfilled.type, payload: { id: '1', message: 'Deleted' } });
    expect(store.getState().pc.pipCheckIns).toHaveLength(0);
  });

  it('clears via clearPipCheckIns', () => {
    const store = createStore();
    store.dispatch({ type: fetchPipCheckIns.fulfilled.type, payload: [{ id: '1' }] });
    store.dispatch(clearPipCheckIns());
    expect(store.getState().pc.pipCheckIns).toEqual([]);
    expect(store.getState().pc.currentPipCheckIn).toBeNull();
  });
});
