import { configureStore } from '@reduxjs/toolkit';
import SmartAttributeSlice, { fetchSmartAttributes, createSmartAttribute, deleteSmartAttribute } from '../SmartAttributeSlice';

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: { smart: SmartAttributeSlice.reducer } });

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

  it('sets currentSmartAttribute on fetchSmartAttributes.fulfilled', () => {
    const store = createStore();
    const attr = { id: '1', specific: 'test' };
    store.dispatch({ type: fetchSmartAttributes.fulfilled.type, payload: attr });
    expect(store.getState().smart.currentSmartAttribute).toEqual(attr);
  });

  it('sets currentSmartAttribute on createSmartAttribute.fulfilled', () => {
    const store = createStore();
    store.dispatch({ type: createSmartAttribute.fulfilled.type, payload: { id: '1' } });
    expect(store.getState().smart.currentSmartAttribute).toEqual({ id: '1' });
  });

  it('clears currentSmartAttribute on deleteSmartAttribute.fulfilled', () => {
    const store = createStore();
    store.dispatch({ type: createSmartAttribute.fulfilled.type, payload: { id: '1' } });
    store.dispatch({ type: deleteSmartAttribute.fulfilled.type, payload: { id: '1', message: 'Deleted' } });
    expect(store.getState().smart.currentSmartAttribute).toBeNull();
  });
});
