import type { ModuleConfig, ModuleCategory } from './types';

let registeredModules: ModuleConfig[] = [];
let moduleMap: Map<string, ModuleConfig> = new Map();

export function registerModules(configs: ModuleConfig[]): void {
  if (process.env.NODE_ENV === 'development') {
    validateRegistry(configs);
  }
  registeredModules = [...configs].sort((a, b) => {
    if (a.category !== b.category) return a.category.localeCompare(b.category);
    return a.navOrder - b.navOrder;
  });
  moduleMap = new Map(registeredModules.map((c) => [c.id, c]));
}

export function getAllModules(): ModuleConfig[] {
  return registeredModules;
}

export function getModuleById(id: string): ModuleConfig | undefined {
  return moduleMap.get(id);
}

export function getModuleByRoute(route: string): ModuleConfig | undefined {
  return registeredModules.find((m) => m.route === route);
}

export function getModulesByCategory(category: ModuleCategory): ModuleConfig[] {
  return registeredModules.filter((m) => m.category === category);
}

function validateRegistry(configs: ModuleConfig[]): void {
  const ids = configs.map((m) => m.id);
  const duplicateIds = ids.filter((id, i) => ids.indexOf(id) !== i);
  if (duplicateIds.length > 0) {
    throw new Error(`Duplicate module IDs: ${duplicateIds.join(', ')}`);
  }

  const routes = configs.map((m) => m.route);
  const duplicateRoutes = routes.filter((r, i) => routes.indexOf(r) !== i);
  if (duplicateRoutes.length > 0) {
    throw new Error(`Duplicate module routes: ${duplicateRoutes.join(', ')}`);
  }
}
