/**
 * Registre runtime des permissions.
 *
 * Le core enregistre ses permissions au boot (initializeZen) ; chaque module
 * externe enregistre les siennes via son hook register(). Le registre alimente
 * à la fois le seed BD (zen-db init) et la validation runtime (updateRole).
 *
 * Le registre est un singleton process-local persisté via Symbol.for sur
 * globalThis pour survivre aux hot-reloads Next.js.
 */

const REGISTRY_KEY = Symbol.for('__ZEN_PERMISSIONS_REGISTRY__');
if (!globalThis[REGISTRY_KEY]) globalThis[REGISTRY_KEY] = new Map();
/** @type {Map<string, { key: string, name: string, description?: string, group_name: string }>} */
const registry = globalThis[REGISTRY_KEY];

export function registerPermission({ key, name, description, group_name }) {
  if (typeof key !== 'string' || !key) {
    throw new TypeError('registerPermission: "key" must be a non-empty string');
  }
  if (typeof name !== 'string' || !name) {
    throw new TypeError(`registerPermission(${key}): "name" must be a non-empty string`);
  }
  if (typeof group_name !== 'string' || !group_name) {
    throw new TypeError(`registerPermission(${key}): "group_name" must be a non-empty string`);
  }
  registry.set(key, { key, name, description: description ?? null, group_name });
}

export function registerPermissions(list) {
  if (!Array.isArray(list)) {
    throw new TypeError('registerPermissions: argument must be an array');
  }
  for (const perm of list) registerPermission(perm);
}

export function getRegisteredPermissions() {
  return [...registry.values()];
}

export function getRegisteredPermissionKeys() {
  return new Set(registry.keys());
}

export function clearRegisteredPermissions() {
  registry.clear();
}
