import express from 'express';
import { Repository } from '../db/repository.js';
import { logger } from '../logger.js';
import { requireAdmin } from './auth.js';
import { createAdminGatewayApi } from './admin-gateway-api.js';

/**
 * AAO Gateway Phase 2a: admin-only CRUD over gateway_virtual_keys, extracted
 * verbatim from createCoreServer (bridge/server.ts). Enabled regardless of
 * gateway.enabled so an admin can prep keys before flipping the gateway on.
 *
 * SECURITY: this endpoint mints `sk-aao-*` bearer tokens that grant
 * access to the LLM gateway. Unlike the generic admin-api (which
 * exposes user-management read paths that are safe to surface in
 * auth-disabled local dev), key issuance has direct production
 * impact. If we mounted it without `requireAdmin` when auth is off,
 * any caller reaching the server could POST to /api/admin/gateway/keys
 * and walk away with a valid gateway bearer. Refuse to mount instead
 * — operators who want key management MUST configure auth.providers.
 */
export function mountAdminGatewayKeysApi(
  app: express.Application,
  deps: { repo: Repository; authActive: boolean },
): void {
  const { repo, authActive } = deps;
  if (authActive) {
    app.use(
      '/api/admin/gateway/keys',
      express.json({ limit: '4kb' }),
      requireAdmin,
      createAdminGatewayApi({
        repo,
        // Already gated above; pass a passthrough so the router doesn't
        // try to double-guard (which would just be a no-op anyway).
        requireAdmin: (_req, _res, next) => next(),
        getUserId: (req) => {
          const u = (req as import('express').Request & {
            user?: { id?: string };
          }).user;
          return u?.id ?? null;
        },
        // Phase 3a F4: when the admin server runs in the same process
        // as the gateway, gateway/bootstrap.ts hangs the shared cache
        // off the Repository so mutations invalidate live cache state.
        // Cross-process setups omit this; the cache's 5s TTL bounds
        // the worst-case stale window.
        keyCache: (repo as unknown as { __gatewayKeyCache?: import('../gateway/key-cache.js').KeyCache })
          .__gatewayKeyCache,
        // Phase 3b post-review: same-process gateway hangs its metrics
        // handle on the Repository so admin mutations can drop the
        // per-key gauge labels (revoke/rotate/delete). No-op in
        // cross-process deploys (the gateway process owns its own
        // registry there).
        gatewayMetrics: (repo as unknown as { __gatewayMetrics?: import('../metrics/gateway-metrics.js').GatewayMetrics })
          .__gatewayMetrics,
      }),
    );
  } else {
    logger.warn(
      '[admin-gateway] /api/admin/gateway/keys NOT mounted (auth disabled). ' +
        'Configure auth.providers in config.yaml to enable virtual key management.',
    );
  }
}
