import { Operations } from '@dynamo/utils'
import { createSlice, PayloadAction } from '@reduxjs/toolkit'

import { types as uiTypes } from '../../ui/system'

export interface MU {
  id: string
  type: 'MU'
  name: string
  useCase: string // Use case
  operation: Operations // Operation
  view?: 'menu'
}

export interface MS {
  id: string
  type: 'MS'
  name: string
  entity: string
  actions: MU[]
}

export interface MI {
  id: string
  type: 'MI'
  name: string
  submenus: Menu[]
}

export type Menu = MS | MI | MU

export interface System {
  name: string
  menus: Menu[]
}

export interface State {
  system?: System
  MS: {
    byId: Record<string, MS>
    allIds: string[]
  }
  MU: {
    byId: Record<string, MU>
    allIds: string[]
  }
}

export const initialState: State = {
  MS: {
    byId: {},
    allIds: [],
  },
  MU: {
    byId: {},
    allIds: [],
  },
}

export interface SystemEntities {
  MS: Record<string, MS>
  MU: Record<string, MU>
}

export interface SystemData {
  system?: System
  entities?: SystemEntities
}

export default createSlice({
  name: 'entities/system',
  initialState,
  reducers: {},
  extraReducers: {
    [uiTypes.fetchMenuSuccess]: (state: State, action: PayloadAction<SystemData>) => {
      const data = action.payload
      state.system = data.system
      if (data.entities) {
        const entities = data.entities
        state.MS.byId = entities.MS
        state.MS.allIds = Object.keys(entities.MS)
        state.MU.byId = entities.MU
        state.MU.allIds = Object.keys(entities.MU)
      }
    },
  },
})
