import { NextRequest, NextResponse } from 'next/server';

export const dynamic = 'force-dynamic';

export async function GET(
  request: NextRequest,
  { params }: { params: Promise<{ requestId: string }> }
) {
  const { requestId } = await params;
  
  // Use container internal URL if available, otherwise fallback
  const backendUrl = process.env.BACKEND_INTERNAL_URL || 'http://api-gateway:4000/v1';
  const targetUrl = `${backendUrl}/workflow/events/${requestId}`;
  
  console.log(`[API Route] Proxying SSE for request ${requestId} to ${targetUrl}`);

  try {
    const response = await fetch(targetUrl, {
      headers: {
        'Accept': 'text/event-stream',
      },
      cache: 'no-store',
    });

    if (!response.ok) {
      console.error(`[API Route] Upstream error: ${response.status} ${response.statusText}`);
      return NextResponse.json(
        { error: `Upstream error: ${response.status}` }, 
        { status: response.status }
      );
    }

    if (!response.body) {
        return NextResponse.json(
            { error: 'No response body from upstream' },
            { status: 502 }
        );
    }

    const stream = response.body;

    return new NextResponse(stream, {
      headers: {
        'Content-Type': 'text/event-stream',
        'Cache-Control': 'no-cache, no-transform',
        'Connection': 'keep-alive',
        'Content-Encoding': 'none',
        'X-Accel-Buffering': 'no', // For Nginx if present
      },
    });
  } catch (error) {
    console.error('[API Route] Proxy failed:', error);
    return NextResponse.json(
      { error: 'Internal Server Error' },
      { status: 500 }
    );
  }
}

