export const dynamic = 'force-dynamic';

export async function OPTIONS() {
  return new Response(null, {
    status: 204,
    headers: {
      'Access-Control-Allow-Origin': '*',
      'Access-Control-Allow-Methods': 'GET, OPTIONS',
    },
  });
}

export async function GET() {
  const encoder = new TextEncoder();
  
  const stream = new ReadableStream({
    start(controller) {
      // Send initial connection event
      controller.enqueue(encoder.encode(`event: connected\ndata: {"status": "listening for A2A intents"}\n\n`));

      // In a real application, you would attach a listener to Redis PubSub or Postgres Listen here.
      // For this implementation, we will send a heartbeat to keep the connection alive.
      const timer = setInterval(() => {
        controller.enqueue(encoder.encode(`event: heartbeat\ndata: {"time": "${new Date().toISOString()}"}\n\n`));
      }, 15000);

      // Handle stream closure
      // Note: Reacting to client disconnect is tricky in Edge/Node standard Request/Response.
      // Usually the server kills the timer when controller.enqueue throws.
      controller.error = () => {
        clearInterval(timer);
      };
    }
  });

  return new Response(stream, {
    headers: {
      'Content-Type': 'text/event-stream',
      'Cache-Control': 'no-cache, no-transform',
      'Connection': 'keep-alive',
      'Access-Control-Allow-Origin': '*',
      'Access-Control-Allow-Methods': 'GET, OPTIONS',
    },
  });
}
