import { ProposalDataContext } from '@agiliza/api/domain'
import { types as fetchTypes } from '@agiliza/redux/useCases/proposalData/context'
import { entries, keys, WithEntityStore } from '@agiliza/utils/method'
import { createSlice, PayloadAction } from '@reduxjs/toolkit'

import { normalizeContext, PROPOSAL_DATA_PREFIX } from '../shared'

export interface Store extends WithEntityStore<ProposalDataContext> {
  // frameworks: EntityStore<Framework>
}

export const initialState: Store = {
  frameworks: { byId: {}, allIds: [] },
  genders: { byId: {}, allIds: [] },
  schoolings: { byId: {}, allIds: [] },
  maritalStatus: { byId: {}, allIds: [] },
  referenceTypes: { byId: {}, allIds: [] },
  homeTypes: { byId: {}, allIds: [] },
  deedRecords: { byId: {}, allIds: [] },
  activitySectors: { byId: {}, allIds: [] },
  settledOPs: { byId: {}, allIds: [] },
  locals: { byId: {}, allIds: [] },
  documentTypes: { byId: {}, allIds: [] },
  monthRatings: { byId: {}, allIds: [] },
}

export default createSlice({
  name: `${PROPOSAL_DATA_PREFIX}/context`,
  initialState,
  reducers: {},
  extraReducers: {
    [fetchTypes.fetchContext.fulfilled]: (state, action: PayloadAction<ProposalDataContext>) => {
      const normalized = normalizeContext(action.payload)
      entries(normalized).forEach(([k, v]) => {
        state[k].byId = v
        state[k].allIds = keys(v)
      })
    },
  },
})
