import type { KbxScreenDefinition, KbxScreenManifestEntry } from '@kbx/contracts'

const screens = new Map<string, KbxScreenDefinition>()

export function registerKbxScreens(definitions: readonly KbxScreenDefinition[]) {
  for (const definition of definitions) {
    if (screens.has(definition.id)) {
      throw new Error(`Duplicate KBX screen id: ${definition.id}`)
    }
    screens.set(definition.id, definition)
  }
}

export function getKbxScreen(id: string) {
  return screens.get(id)
}

export function listKbxScreens(): KbxScreenDefinition[] {
  return [...screens.values()].sort((a, b) => a.id.localeCompare(b.id))
}

export function toKbxScreenManifest(routeById: Record<string, string> = {}): KbxScreenManifestEntry[] {
  return listKbxScreens().map(screen => ({
    id: screen.id,
    version: screen.version,
    module: screen.module,
    type: screen.type,
    templateCode: screen.templateCode,
    title: screen.title,
    route: routeById[screen.id],
    helpKey: screen.helpKey,
    requiredPermissions: screen.permissions ?? [],
  }))
}
