import { configureStore } from '@reduxjs/toolkit';
import QuestionsSlice from '../QuestionsSlice';

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: { q: QuestionsSlice.reducer } });

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

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

  it('populates questions and meta on fetch fulfilled', () => {
    const store = createStore();
    const meta = { current_page: 1, last_page: 1, per_page: 15, total: 1 };
    store.dispatch({ type: 'questions/fetch/fulfilled', payload: { data: [{ id: '1' }], meta } });
    expect(store.getState().q.questions).toEqual([{ id: '1' }]);
    expect(store.getState().q.meta).toEqual(meta);
  });

  it('prepends on create fulfilled', () => {
    const store = createStore();
    const meta = { current_page: 1, last_page: 1, per_page: 15, total: 1 };
    store.dispatch({ type: 'questions/fetch/fulfilled', payload: { data: [{ id: '1' }], meta } });
    store.dispatch({ type: 'questions/create/fulfilled', payload: { id: '2' } });
    expect(store.getState().q.questions[0]).toEqual({ id: '2' });
  });

  it('updates in-place on update fulfilled', () => {
    const store = createStore();
    const meta = { current_page: 1, last_page: 1, per_page: 15, total: 1 };
    store.dispatch({ type: 'questions/fetch/fulfilled', payload: { data: [{ id: '1', text: 'Old' }], meta } });
    store.dispatch({ type: 'questions/update/fulfilled', payload: { id: '1', text: 'New' } });
    expect(store.getState().q.questions[0].text).toBe('New');
  });

  it('removes on delete fulfilled', () => {
    const store = createStore();
    const meta = { current_page: 1, last_page: 1, per_page: 15, total: 1 };
    store.dispatch({ type: 'questions/fetch/fulfilled', payload: { data: [{ id: '1' }], meta } });
    store.dispatch({ type: 'questions/delete/fulfilled', payload: { id: '1', message: 'Deleted' } });
    expect(store.getState().q.questions).toEqual([]);
  });
});
