import { configureStore } from '@reduxjs/toolkit';
import InterviewsSlice, { fetchInterviews, fetchInterview, fetchUpcomingInterviews, clearInterview } from '../InterviewsSlice';

jest.mock('@/services/api/api', () => ({ apiGet: jest.fn(), apiPost: jest.fn(), apiPut: jest.fn(), apiDelete: jest.fn(), apiDownloadBlob: 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: { interviews: InterviewsSlice.reducer } });

describe('InterviewsSlice', () => {
  it('has correct initial state', () => {
    const state = createStore().getState().interviews;
    expect(state.interviews).toEqual([]);
    expect(state.interview).toBeNull();
    expect(state.upcomingInterviews).toEqual([]);
    expect(state.pendingFeedbackInterviews).toEqual([]);
    expect(state.history).toEqual([]);
    expect(state.stats).toBeNull();
    expect(state.meta).toBeNull();
    expect(state.loading).toBe(false);
    expect(state.actionLoading).toBe(false);
    expect(state.error).toBeNull();
  });

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

  it('populates data on fetchInterviews.fulfilled', () => {
    const store = createStore();
    const payload = { data: [{ id: '1' }], meta: { total: 1 } } as any;
    store.dispatch(fetchInterviews.fulfilled(payload, 'req'));
    expect(store.getState().interviews.interviews).toEqual(payload.data);
    expect(store.getState().interviews.meta).toEqual(payload.meta);
    expect(store.getState().interviews.loading).toBe(false);
  });

  it('populates single interview on fetchInterview.fulfilled', () => {
    const store = createStore();
    const payload = { data: { id: '1', status: 'scheduled' } } as any;
    store.dispatch(fetchInterview.fulfilled(payload, 'req', '1'));
    expect(store.getState().interviews.interview).toEqual(payload.data);
  });

  it('populates upcoming interviews on fetchUpcomingInterviews.fulfilled', () => {
    const store = createStore();
    const payload = { data: [{ id: '2' }] } as any;
    store.dispatch(fetchUpcomingInterviews.fulfilled(payload, 'req', undefined));
    expect(store.getState().interviews.upcomingInterviews).toEqual(payload.data);
  });

  it('clears interview on clearInterview', () => {
    const store = createStore();
    store.dispatch(fetchInterview.fulfilled({ data: { id: '1' } } as any, 'req', '1'));
    store.dispatch(clearInterview());
    expect(store.getState().interviews.interview).toBeNull();
  });
});
