import { configureStore } from '@reduxjs/toolkit';
import AppraisalRatingSlice, { fetchAppraisalRatings, createAppraisalRating, deleteAppraisalRating } from '../AppraisalRatingSlice';

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: { ratings: AppraisalRatingSlice.reducer } });

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

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

  it('populates on fetch fulfilled', () => {
    const store = createStore();
    const payload = { data: [{ id: '1' }], meta: {}, links: {} };
    store.dispatch({ type: fetchAppraisalRatings.fulfilled.type, payload });
    expect(store.getState().ratings.appraisalRatings).toEqual(payload.data);
  });

  it('prepends on create fulfilled', () => {
    const store = createStore();
    store.dispatch({ type: createAppraisalRating.fulfilled.type, payload: { id: '1' } });
    expect(store.getState().ratings.appraisalRatings[0]).toEqual({ id: '1' });
  });

  it('removes on delete fulfilled', () => {
    const store = createStore();
    store.dispatch({
      type: fetchAppraisalRatings.fulfilled.type,
      payload: { data: [{ id: '1' }, { id: '2' }], meta: undefined, links: undefined },
    });
    store.dispatch({
      type: deleteAppraisalRating.fulfilled.type,
      payload: { id: '1', message: 'Deleted' },
    });
    expect(store.getState().ratings.appraisalRatings).toHaveLength(1);
  });
});
