import { normalize, schema } from 'normalizr'

import { City, GetContext, State } from '@agiliza/api/domain/authentication'
import { NormalizedEntity } from '@agiliza/utils/method'

export interface NormalizedContext {
  states: NormalizedEntity<State>
  cities: NormalizedEntity<City>
}

const states = new schema.Array(new schema.Entity('states'))
const cities = new schema.Array(new schema.Entity('cities'))

const contextEntities = new schema.Object({ states, cities })

export const normalizeContext = (context: GetContext['Output']) => {
  const { entities } = normalize(context, contextEntities)
  const normalizedEntities = entities as unknown as NormalizedContext
  return normalizedEntities
}
