import { City, GetContext, State } from '@agiliza/api/domain/authentication'
import { types as fetchTypes } from '@agiliza/redux/useCases/authentication'
import { EntityStore, keys } from '@agiliza/utils/method'
import { createSlice, PayloadAction } from '@reduxjs/toolkit'

import { PREFIX } from '../shared'
import { normalizeContext } from './shared'

export interface Store {
  states: EntityStore<State>
  cities: EntityStore<City>
}

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

export default createSlice({
  name: `${PREFIX}/authentication`,
  initialState,
  reducers: {},
  extraReducers: {
    [fetchTypes.getContext.fulfilled]: (state, action: PayloadAction<GetContext['Output']>) => {
      const normalized = normalizeContext(action.payload)
      console.log(normalized)

      state.states.byId = normalized.states
      state.states.allIds = keys(normalized.states)

      state.cities.byId = normalized.cities
      state.cities.allIds = keys(normalized.cities)
    },
  },
})
