import { GetSubProducts, SubProduct } 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 { normalizeSubproducts, SIMULATION_PREFIX } from '../shared'

export interface Store {
  subproducts: EntityStore<SubProduct>
}

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

export default createSlice({
  name: `${SIMULATION_PREFIX}/simulation`,
  initialState,
  reducers: {},
  extraReducers: {
    [fetchTypes.getSubproducts.fulfilled]: (state, action: PayloadAction<GetSubProducts['Output']>) => {
      const normalized = normalizeSubproducts(action.payload)

      state.subproducts.byId = syncById(state.subproducts, normalized.subproducts)
      state.subproducts.allIds = syncAllIds(state.subproducts, normalized.subproducts)
    },
  },
})
