import { configureStore } from '@reduxjs/toolkit';
import { HRImportsSlice, previewImportFile, validateHRImport, executeHRImport, fetchImportStatus, downloadHRImportTemplate, setColumnMapping, updateColumnMapping, clearImportState, validateIDCardImport } from '../HRImportsSlice';

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

describe('HRImportsSlice', () => {
  it('has correct initial state', () => {
    const store = createStore();
    const state = store.getState().hrImports;
    expect(state.previewData).toBeNull();
    expect(state.columnMapping).toEqual({});
    expect(state.validationResult).toBeNull();
    expect(state.importResult).toBeNull();
    expect(state.importBatch).toBeNull();
    expect(state.previewing).toBe(false);
    expect(state.validating).toBe(false);
    expect(state.importing).toBe(false);
    expect(state.downloadingTemplate).toBe(false);
    expect(state.downloadingFailedRows).toBe(false);
    expect(state.idCardTempFilePath).toBeNull();
    expect(state.idCardTempImagesPath).toBeNull();
    expect(state.error).toBeNull();
  });

  describe('reducers', () => {
    it('setColumnMapping sets mapping', () => {
      const store = createStore();
      const mapping = { Name: 'firstname', Email: 'email' };
      store.dispatch(setColumnMapping(mapping));
      expect(store.getState().hrImports.columnMapping).toEqual(mapping);
    });

    it('updateColumnMapping updates single entry', () => {
      const store = createStore();
      store.dispatch(setColumnMapping({ Name: 'firstname' }));
      store.dispatch(updateColumnMapping({ header: 'Name', field: 'lastname' }));
      expect(store.getState().hrImports.columnMapping.Name).toBe('lastname');
    });

    it('clearImportState resets fields', () => {
      const store = createStore();
      store.dispatch(setColumnMapping({ a: 'b' }));
      store.dispatch(clearImportState());
      expect(store.getState().hrImports.columnMapping).toEqual({});
      expect(store.getState().hrImports.previewData).toBeNull();
    });
  });

  describe('previewImportFile', () => {
    it('sets previewing on pending', () => {
      const store = createStore();
      store.dispatch({ type: previewImportFile.pending.type });
      expect(store.getState().hrImports.previewing).toBe(true);
    });

    it('populates previewData and mapping on fulfilled', () => {
      const store = createStore();
      const payload = {
        headers: ['Name', 'Email'],
        sample_rows: [['John', 'john@test.com']],
        suggested_mapping: { Name: 'firstname', Email: 'email' },
        available_fields: [{ key: 'firstname', label: 'First Name' }],
        sheet_names: ['Sheet1'],
        active_sheet: 'Sheet1',
        header_row: 1,
        total_data_rows: 10,
        temp_file_path: '/tmp/file.xlsx',
      };
      store.dispatch({ type: previewImportFile.fulfilled.type, payload });
      expect(store.getState().hrImports.previewData).toEqual(payload);
      expect(store.getState().hrImports.columnMapping).toEqual(payload.suggested_mapping);
    });
  });

  describe('validateHRImport', () => {
    it('sets validating on pending', () => {
      const store = createStore();
      store.dispatch({ type: validateHRImport.pending.type });
      expect(store.getState().hrImports.validating).toBe(true);
    });

    it('sets validationResult on fulfilled', () => {
      const store = createStore();
      const result = { message: 'Valid', validate_only: true, imported_count: 0, updated_count: 0, failed_count: 0, processed_count: 10, failed_rows_file: null, failed_rows_download_url: null };
      store.dispatch({ type: validateHRImport.fulfilled.type, payload: result });
      expect(store.getState().hrImports.validationResult).toEqual(result);
      expect(store.getState().hrImports.validating).toBe(false);
    });
  });

  describe('executeHRImport', () => {
    it('sets importing on pending', () => {
      const store = createStore();
      store.dispatch({ type: executeHRImport.pending.type });
      expect(store.getState().hrImports.importing).toBe(true);
    });

    it('sets importBatch on fulfilled', () => {
      const store = createStore();
      store.dispatch({ type: executeHRImport.fulfilled.type, payload: { batch_id: 'b1', message: 'Started' } });
      expect(store.getState().hrImports.importBatch?.batch_id).toBe('b1');
      expect(store.getState().hrImports.importing).toBe(false);
    });
  });

  describe('fetchImportStatus', () => {
    it('sets importBatch on fulfilled', () => {
      const store = createStore();
      const status = { batch_id: 'b1', progress: 100, finished: true, cancelled: false, total_jobs: 1, pending_jobs: 0, processed_jobs: 1, failed_jobs: 0, imported_count: 5, updated_count: 0, failed_count: 0, processed_count: 5 };
      store.dispatch({ type: fetchImportStatus.fulfilled.type, payload: status });
      expect(store.getState().hrImports.importBatch).toEqual(status);
      expect(store.getState().hrImports.importResult?.imported_count).toBe(5);
    });
  });

  describe('downloadHRImportTemplate', () => {
    it('sets downloadingTemplate on pending', () => {
      const store = createStore();
      store.dispatch({ type: downloadHRImportTemplate.pending.type });
      expect(store.getState().hrImports.downloadingTemplate).toBe(true);
    });

    it('resets downloadingTemplate on fulfilled', () => {
      const store = createStore();
      store.dispatch({ type: downloadHRImportTemplate.fulfilled.type });
      expect(store.getState().hrImports.downloadingTemplate).toBe(false);
    });
  });

  describe('validateIDCardImport', () => {
    it('sets temp paths on fulfilled', () => {
      const store = createStore();
      const payload = { message: 'Valid', validate_only: true, imported_count: 0, updated_count: 0, failed_count: 0, processed_count: 5, failed_rows_file: null, failed_rows_download_url: null, temp_file_path: '/tmp/f.xlsx', temp_images_path: '/tmp/imgs', total_images: 3 };
      store.dispatch({ type: validateIDCardImport.fulfilled.type, payload });
      expect(store.getState().hrImports.idCardTempFilePath).toBe('/tmp/f.xlsx');
      expect(store.getState().hrImports.idCardTempImagesPath).toBe('/tmp/imgs');
    });
  });
});
