/**
 * Catch-all proxy from the Forge web app to the chat-standalone server
 * (127.0.0.1:$CHAT_PORT, default 8408). Lets the in-app /chat page hit
 * the same routes the browser extension uses, without exposing 8408
 * publicly or re-implementing auth.
 *
 * The middleware on this server (port 8403) gates access via cookie/
 * token; once a request reaches here it's authenticated, so we can
 * forward to loopback without further checks.
 *
 * SSE pass-through: when upstream returns text/event-stream we stream
 * the body verbatim so the /chat page gets live tokens.
 */

import { NextResponse } from 'next/server';

const CHAT_BASE = `http://127.0.0.1:${process.env.CHAT_PORT || 8408}`;

async function forward(
  req: Request,
  ctx: { params: Promise<{ path: string[] }> },
): Promise<Response> {
  const { path } = await ctx.params;
  const segs = (path || []).map(encodeURIComponent).join('/');
  const search = new URL(req.url).search;
  const target = `${CHAT_BASE}/api/${segs}${search}`;

  const headers: Record<string, string> = {};
  const ct = req.headers.get('content-type');
  if (ct) headers['content-type'] = ct;
  const accept = req.headers.get('accept');
  if (accept) headers['accept'] = accept;

  const init: RequestInit = { method: req.method, headers };
  if (req.method !== 'GET' && req.method !== 'HEAD') {
    init.body = await req.text();
  }

  let upstream: Response;
  try {
    upstream = await fetch(target, init);
  } catch (err) {
    return NextResponse.json(
      {
        error: 'chat backend unreachable',
        detail: err instanceof Error ? err.message : String(err),
        target,
      },
      { status: 502 },
    );
  }

  const upstreamCt = upstream.headers.get('content-type') || '';
  if (upstreamCt.includes('text/event-stream')) {
    return new Response(upstream.body, {
      status: upstream.status,
      headers: {
        'content-type': 'text/event-stream',
        'cache-control': 'no-cache, no-transform',
        connection: 'keep-alive',
        'x-accel-buffering': 'no',
      },
    });
  }

  return new Response(upstream.body, {
    status: upstream.status,
    headers: { 'content-type': upstreamCt || 'application/json' },
  });
}

export async function GET(req: Request, ctx: { params: Promise<{ path: string[] }> }) {
  return forward(req, ctx);
}
export async function POST(req: Request, ctx: { params: Promise<{ path: string[] }> }) {
  return forward(req, ctx);
}
export async function PATCH(req: Request, ctx: { params: Promise<{ path: string[] }> }) {
  return forward(req, ctx);
}
export async function DELETE(req: Request, ctx: { params: Promise<{ path: string[] }> }) {
  return forward(req, ctx);
}
