// Streaming proxy for the backend LNbits SSE endpoint.
//
// Next.js `rewrites` buffer `text/event-stream` responses, so payment events
// never reach the browser in real time when going through the same-origin proxy.
// This route handler streams the backend response body straight through with
// anti-buffering headers, so EventSource on the booking page works in dev and
// proxyless deployments. A route handler takes precedence over the rewrite.

export const dynamic = 'force-dynamic';

const BACKEND_URL = process.env.BACKEND_URL || 'http://localhost:3001';

export async function GET(
  request: Request,
  { params }: { params: { ticketId: string } }
) {
  const upstream = await fetch(
    `${BACKEND_URL}/api/lnbits/stream/${params.ticketId}`,
    {
      headers: { Accept: 'text/event-stream' },
      signal: request.signal,
    }
  );

  // If the ticket is already confirmed the backend may answer with JSON instead
  // of a stream; pass that through unchanged so the client can handle it.
  const contentType = upstream.headers.get('content-type') || '';
  if (!contentType.includes('text/event-stream')) {
    return new Response(upstream.body, {
      status: upstream.status,
      headers: { 'Content-Type': contentType || 'application/json' },
    });
  }

  return new Response(upstream.body, {
    status: upstream.status,
    headers: {
      'Content-Type': 'text/event-stream; charset=utf-8',
      'Cache-Control': 'no-cache, no-transform',
      Connection: 'keep-alive',
      'X-Accel-Buffering': 'no',
    },
  });
}
