/**
 * ZEN Initialization
 *
 * Wires core feature dependencies into the API router.
 * This is the composition root — the only place that connects features to core.
 *
 * @example
 * // instrumentation.js
 * export async function register() {
 *   if (process.env.NEXT_RUNTIME === 'nodejs') {
 *     const { initializeZen } = await import('@zen/core');
 *     await initializeZen();
 *   }
 * }
 */

import { configureRouter, registerFeatureRoutes, clearRouterConfig, clearFeatureRoutes } from '@zen/core/api';
import { registerStoragePolicies, clearStorageConfig } from '@zen/core/storage';
import { validateSession } from '../../features/auth/lib/session.js';
import { routes as authRoutes } from '../../features/auth/api.js';
import { storageAccessPolicies } from '../../features/auth/storage-policies.js';
import { done, warn } from './logger.js';

const ZEN_INIT_KEY = Symbol.for('__ZEN_INITIALIZED__');

export async function initializeZen() {
  if (typeof window !== 'undefined') {
    return { skipped: true, reason: 'client-side' };
  }

  if (globalThis[ZEN_INIT_KEY]) {
    warn('ZEN: already initialized, skipping');
    return { skipped: true, reason: 'already-initialized' };
  }

  globalThis[ZEN_INIT_KEY] = true;

  configureRouter({ resolveSession: validateSession });
  registerFeatureRoutes(authRoutes);
  registerStoragePolicies(storageAccessPolicies);

  done('ZEN: ready');

  return {};
}

export function resetZenInitialization() {
  globalThis[ZEN_INIT_KEY] = false;
  clearRouterConfig();
  clearFeatureRoutes();
  clearStorageConfig();
  warn('ZEN: initialization reset');
}
