/**
 * Phase 3c — read-only admin endpoint for the same-process gateway
 * mount status.
 *
 * The Gateway Server settings page polls this to render the status
 * badge (running / disabled / starting / etc.) and surface any
 * validation errors blocking a start. There is no PATCH/POST here —
 * enabling / disabling the gateway is done through the existing
 * /api/config PUT (the config-changed event picks up the new value
 * and the mount handle reacts).
 */
import { Router, type Request, type Response } from 'express';
import type { GatewayMountHandle } from './gateway-mount.js';
import type { ConfigManager } from '../config-manager.js';
import { readGatewayConfig } from '../gateway/config.js';

export interface AdminGatewayStatusDeps {
  /**
   * Mount handle from createCoreServer. May be null when the bridge
   * was created without a ConfigManager — in that case the endpoint
   * reports the gateway as `unavailable` so the UI knows hot reload
   * isn't supported in this deploy.
   */
  mount: GatewayMountHandle | null;
  /** ConfigManager so we can read the current desired-enabled flag. */
  configManager: ConfigManager | null;
  /**
   * Port the worker bridge is listening on. Reported to the UI so the
   * Gateway Server form can show `mounted at /v1 (port 9876)` instead
   * of forcing the user to remember the port.
   */
  workerPort: number;
}

export function createAdminGatewayStatusRouter(deps: AdminGatewayStatusDeps): Router {
  const router = Router();

  router.get('/', (_req: Request, res: Response) => {
    const desiredEnabled = (() => {
      try {
        if (!deps.configManager) return null;
        return readGatewayConfig(deps.configManager.getConfig()).enabled;
      } catch {
        return null;
      }
    })();

    if (!deps.mount) {
      res.json({
        state: 'unavailable',
        enabled: desiredEnabled,
        errors: [],
        mounted: false,
        sharedPort: deps.workerPort,
        message: 'gateway hot-reload unsupported in this deploy (no ConfigManager)',
      });
      return;
    }

    res.json({
      state: deps.mount.getState(),
      enabled: desiredEnabled,
      errors: deps.mount.getErrors(),
      mounted: deps.mount.getState() === 'running',
      // The gateway runs on the same TCP port as the worker UI in
      // same-process mode. The UI uses this to hint the user.
      sharedPort: deps.workerPort,
    });
  });

  return router;
}
