import type { CrudHandlers } from "@c/crud/crudTypes"

// Store CRUD handlers in a simple object
const handlers: Record<string, CrudHandlers<any>> = {}
const scopes: Record<string, Set<string>> = {}

export const registerCrudHandlers = <T>(
  type: string,
  crudHandlers: CrudHandlers<T>,
  scope = "core",
): void => {
  if (handlers[type]) {
    throw new Error(`CRUD handlers for type "${type}" are already registered`)
  }

  handlers[type] = crudHandlers

  // Register scope
  scopes[scope] = scopes[scope] || new Set()
  scopes[scope].add(type)
}

export const getCrudHandlers = <T>(type: string): CrudHandlers<T> | undefined =>
  handlers[type]

export const getAllCrudHandlers = (): Record<string, CrudHandlers<any>> =>
  handlers

export const getCrudHandlersByScope = (scope: string): CrudHandlers<any>[] =>
  Array.from(scopes[scope] || []).map((type) => handlers[type])

export const getAllTypes = (): string[] => Object.keys(handlers)
