import { configureStore } from '@reduxjs/toolkit';
import PensionSetupSlice, {
  fetchPensionSetupCountries,
  fetchPensionSetupStatus,
  applyPensionTemplate,
} from '../PensionSetupSlice';

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

jest.mock('antd', () => ({
  message: { success: jest.fn(), error: jest.fn(), warning: jest.fn() },
}));

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

const { apiGet, apiPost } = require('@/services/api/api');

const createTestStore = () =>
  configureStore({ reducer: { pensionSetup: PensionSetupSlice.reducer } });

describe('PensionSetupSlice', () => {
  beforeEach(() => jest.clearAllMocks());

  it('has correct initial state', () => {
    const store = createTestStore();
    const state = store.getState().pensionSetup;
    expect(state.countries).toEqual([]);
    expect(state.status).toBeNull();
    expect(state.loading).toBe(false);
    expect(state.applying).toBe(false);
    expect(state.error).toBeNull();
  });

  describe('fetchPensionSetupCountries', () => {
    it('populates countries on fulfilled', async () => {
      const countries = [{ code: 'GH', name: 'Ghana' }];
      apiGet.mockResolvedValue({ data: countries });
      const store = createTestStore();
      await store.dispatch(fetchPensionSetupCountries());
      expect(store.getState().pensionSetup.countries).toEqual(countries);
      expect(store.getState().pensionSetup.loading).toBe(false);
    });

    it('sets error on rejected', async () => {
      apiGet.mockRejectedValue(new Error('fail'));
      const store = createTestStore();
      await store.dispatch(fetchPensionSetupCountries());
      expect(store.getState().pensionSetup.error).toBeTruthy();
    });
  });

  describe('fetchPensionSetupStatus', () => {
    it('populates status on fulfilled', async () => {
      const status = { configured: true, country_code: 'GH' };
      apiGet.mockResolvedValue({ data: status });
      const store = createTestStore();
      await store.dispatch(fetchPensionSetupStatus());
      expect(store.getState().pensionSetup.status).toEqual(status);
    });
  });

  describe('applyPensionTemplate', () => {
    it('sets applying on pending and clears on fulfilled', async () => {
      apiPost.mockResolvedValue({ data: { message: 'Applied', country_code: 'GH', country_name: 'Ghana' } });
      const store = createTestStore();
      const promise = store.dispatch(applyPensionTemplate('GH'));
      expect(store.getState().pensionSetup.applying).toBe(true);
      await promise;
      expect(store.getState().pensionSetup.applying).toBe(false);
    });
  });
});
