import { GetProjects, Project, ProjectContext } from '@agiliza/api/domain'
import { types as fetchTypes } from '@agiliza/redux/useCases/project'
import { EntityStore, entries, keys, WithEntityStore } from '@agiliza/utils/method'
import { createSlice, PayloadAction } from '@reduxjs/toolkit'

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

export interface Store extends WithEntityStore<ProjectContext> {
  projects: EntityStore<Project>
}

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

export default createSlice({
  name: `${PREFIX}/context`,
  initialState,
  reducers: {},
  extraReducers: {
    [fetchTypes.getContext.fulfilled]: (state, action: PayloadAction<ProjectContext>) => {
      const normalized = normalizeContext(action.payload)
      entries(normalized).forEach(([k, v]) => {
        state[k].byId = v
        state[k].allIds = keys(v)
      })
    },
    [fetchTypes.getProjects.fulfilled]: (state, action: PayloadAction<GetProjects['Output']>) => {
      const normalized = normalizeProjects(action.payload)
      state.projects.byId = normalized.projects
      state.projects.allIds = keys(normalized.projects)
    },
  },
})
