import { SimulationCategory } from '@agiliza/api/domain'
import { types as fetchTypes } from '@agiliza/redux/useCases/simulation'
import { EntityStore, syncAllIds, syncById } from '@agiliza/utils/method'
import { createSlice, PayloadAction } from '@reduxjs/toolkit'

import { normalizeSimulationCategories, SIMULATION_PREFIX } from '../shared'

export interface Store {
  simulationCategories: EntityStore<SimulationCategory>
}

export const initialState: Store = {
  simulationCategories: { byId: {}, allIds: [] },
}

export default createSlice({
  name: `${SIMULATION_PREFIX}/context`,
  initialState,
  reducers: {},
  extraReducers: {
    [fetchTypes.fetchSimulationCategories.fulfilled]: (state, action: PayloadAction<SimulationCategory[]>) => {
      const normalized = normalizeSimulationCategories(action.payload)
      state.simulationCategories.byId = syncById(state.simulationCategories, normalized.simulationCategories)
      state.simulationCategories.allIds = syncAllIds(state.simulationCategories, normalized.simulationCategories)
    },
  },
})
