/**
 * Bridge-info — exposes the browser-bridge port so the Forge extension
 * can derive the right WebSocket URL when connecting to a non-default
 * Forge instance.
 *
 * The default prod port is 8407, but dev-test (4007) or any custom
 * deployment (--port + offset) lives on a different one. The extension
 * used to hardcode 8407, which silently routed all WS traffic to a
 * neighbouring Forge instance whenever the user pointed at port 4000.
 *
 * Public read endpoint — no auth required. The bridge port is not a
 * secret; the bridge itself still requires a valid Forge token on the
 * WS hello frame before serving traffic.
 */

import { NextResponse } from 'next/server';

export const runtime = 'nodejs';
export const dynamic = 'force-dynamic';

export function GET(req: Request) {
  const url = new URL(req.url);
  const port = Number(process.env.BRIDGE_PORT) || 8407;
  // Caller-visible host: prefer the host header so extensions get the
  // right address whether they reached Forge via localhost, IP, or
  // tunnel hostname. Strip the original port — the WS host stays the
  // same, only the port changes.
  const host = (req.headers.get('host') || url.host).split(':')[0];
  const proto = url.protocol === 'https:' ? 'wss:' : 'ws:';
  return NextResponse.json({
    bridge_port: port,
    ws_url: `${proto}//${host}:${port}/ws`,
  });
}
