import { normalize, schema } from 'normalizr'

import { Project, ProjectContext } from '@agiliza/api/domain'
import { NormalizedEntity, WithNormalizedEntity } from '@agiliza/utils/method'

export type NormalizedContext = WithNormalizedEntity<ProjectContext>

export interface NormalizedProjects {
  projects: NormalizedEntity<Project>
}

const projectsSchema = new schema.Array(new schema.Entity('projects'))

const contextSchemas: Record<keyof ProjectContext, any> = {
  statuses: new schema.Array(new schema.Entity('statuses')),
}

export const normalizeContext = (context: ProjectContext) => {
  const { entities } = normalize(context, contextSchemas)
  const normalizedEntities = entities as unknown as NormalizedContext
  return normalizedEntities
}

export const normalizeProjects = (projects: Project[]) => {
  const { entities } = normalize(projects, projectsSchema)
  const normalizedEntities = entities as unknown as NormalizedProjects
  return normalizedEntities
}
