/**
 * Thin proxy helper — forwards a Next.js request to chat-standalone
 * (127.0.0.1:$CHAT_PORT, default 8408). Auth is enforced by the Next
 * middleware before we get here; chat-standalone itself is loopback-only.
 */

const CHAT_PORT = Number(process.env.CHAT_PORT) || 8408;

export async function proxyToChat(req: Request, path: string): Promise<Response> {
  const url = new URL(req.url);
  const target = `http://127.0.0.1:${CHAT_PORT}${path}${url.search || ''}`;

  // Pass the body through verbatim for POST/PATCH. GET/DELETE go without.
  const init: RequestInit = {
    method: req.method,
    headers: { 'content-type': 'application/json' },
    body: req.method === 'GET' || req.method === 'DELETE' || req.method === 'HEAD'
      ? undefined
      : await req.text(),
  };

  let upstream: Response;
  try {
    upstream = await fetch(target, init);
  } catch (e) {
    return new Response(JSON.stringify({ error: `chat service unreachable on ${CHAT_PORT}: ${(e as Error).message}` }), {
      status: 502, headers: { 'content-type': 'application/json' },
    });
  }

  // For SSE streams, pipe the body through as a streaming response so
  // events reach the browser as they arrive.
  const ct = upstream.headers.get('content-type') || '';
  if (ct.startsWith('text/event-stream') && upstream.body) {
    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',
      },
    });
  }

  const body = await upstream.text();
  return new Response(body, {
    status: upstream.status,
    headers: { 'content-type': upstream.headers.get('content-type') || 'application/json' },
  });
}
