/**
 * Roles Redux Slice
 *
 * Extends the base entity slice with custom widget management actions.
 */

import { createAsyncThunk, createReducer } from '@reduxjs/toolkit';
import axios from 'axios';
import { createEntitySlice } from '../createEntitySlice';
import type { Role } from '../../types/entities';
import type { EntitySliceState } from '../../types/redux';

// Extended state type for roles with widget support
interface RolesSliceState extends EntitySliceState<Role> {
  rolesWidgets: Array<{ id: string; [key: string]: unknown }>;
}

// Create base entity slice with standard CRUD operations
const {
  slice,
  actions,
  reducer: baseReducer,
} = createEntitySlice<Role>({
  name: 'roles',
  endpoint: 'roles',
  singularName: 'Role',
});

// Custom thunks specific to roles
export const removeWidget = createAsyncThunk(
  'openai/removeWidget',
  async (payload: { id: string; roleId: string; widgetId: string }) => {
    const result = await axios.delete(`openai/roles-info/${payload.id}`, {
      params: {
        roleId: payload.roleId,
        infoId: payload.widgetId,
        key: 'widgets',
      },
    });
    return result.data;
  },
);

export const fetchWidgets = createAsyncThunk(
  'openai/fetchWidgets',
  async (roleId: string) => {
    const result = await axios.get(
      `openai/info-by-key?key=widgets&roleId=${roleId}`,
    );
    return result.data;
  },
);

// Initial state with widgets
const initialWidgetsState: {
  rolesWidgets: Array<{ id: string; [key: string]: unknown }>;
} = {
  rolesWidgets: [],
};

// Combined reducer that extends base reducer with widget handling
const combinedReducer = createReducer(
  {
    ...baseReducer(undefined, { type: '' }),
    ...initialWidgetsState,
  } as RolesSliceState,
  (builder) => {
    // Handle fetchWidgets.fulfilled
    builder.addCase(fetchWidgets.fulfilled, (state, action) => {
      state.rolesWidgets = action.payload || [];
    });
    // Handle removeWidget.fulfilled - refresh will be triggered by component
    builder.addCase(removeWidget.fulfilled, () => {
      // Widget removed, component will refetch
    });
    // Pass all other actions to base reducer
    builder.addDefaultCase((state, action) => {
      const baseResult = baseReducer(state, action);
      return { ...baseResult, rolesWidgets: state.rolesWidgets };
    });
  },
);

// Export standard CRUD actions
export const {
  fetch,
  create,
  update,
  deleteItem,
  deleteItemsByIds,
  uploadCsv,
  setRefetch,
} = actions;
export const rolesSlice = slice;

export default combinedReducer;
