/**
 * Browser bridge HTTP API — thin proxy from Next.js into the standalone.
 *
 * The standalone (lib/browser-bridge-standalone.ts) holds the WebSocket
 * server and per-extension token state. Next.js exposes a small surface
 * for in-Forge code paths (chat backend, settings UI):
 *
 *   GET  /api/browser-bridge?action=status
 *   POST /api/browser-bridge { action: "rpc", method, params }
 *   POST /api/browser-bridge { action: "push", topic, payload }
 *
 * Pairing is gone — the extension authenticates with the user's existing
 * Forge token over the WS hello frame.
 */

import { NextResponse } from 'next/server';

const BRIDGE_PORT = Number(process.env.BRIDGE_PORT) || 8407;
const BRIDGE_URL = `http://localhost:${BRIDGE_PORT}`;

async function forward(path: string, init?: RequestInit): Promise<NextResponse> {
  try {
    const r = await fetch(`${BRIDGE_URL}${path}`, init);
    const text = await r.text();
    // Pass through JSON if possible
    try {
      return NextResponse.json(JSON.parse(text), { status: r.status });
    } catch {
      return new NextResponse(text, { status: r.status });
    }
  } catch (e) {
    return NextResponse.json(
      { error: 'bridge_unreachable', detail: (e as Error).message },
      { status: 502 },
    );
  }
}

export async function GET(req: Request) {
  const url = new URL(req.url);
  const action = url.searchParams.get('action') || 'status';
  if (action === 'status') {
    return forward('/api/status');
  }
  return NextResponse.json({ error: 'unknown action' }, { status: 400 });
}

export async function POST(req: Request) {
  const body = await req.json().catch(() => ({}));
  const action = body?.action;

  switch (action) {
    case 'rpc':
      return forward('/api/rpc', {
        method: 'POST',
        headers: { 'content-type': 'application/json' },
        body: JSON.stringify({ method: body.method, params: body.params }),
      });

    case 'push':
      return forward('/api/push', {
        method: 'POST',
        headers: { 'content-type': 'application/json' },
        body: JSON.stringify({ topic: body.topic, payload: body.payload }),
      });

    default:
      return NextResponse.json({ error: 'unknown action' }, { status: 400 });
  }
}
