import { NextRequest, NextResponse } from 'next/server';
import { getRecentEvents } from '@/lib/db';
import { addClient, removeClient } from '@/lib/sse';

export const dynamic = 'force-dynamic';

export async function GET(request: NextRequest) {
  const { searchParams } = new URL(request.url);
  const stream = searchParams.get('stream');

  // If not requesting SSE, return JSON snapshot
  if (stream !== 'true') {
    try {
      const events = getRecentEvents(20);
      return NextResponse.json(events);
    } catch (error) {
      console.error('[activity] Failed to get recent events:', error);
      return NextResponse.json([], { status: 500 });
    }
  }

  // SSE stream mode
  const encoder = new TextEncoder();
  let clientId: string | null = null;

  const readable = new ReadableStream({
    start(controller) {
      clientId = addClient(controller);

      // Send initial batch as a regular data event
      try {
        const events = getRecentEvents(20);
        const payload = `event: init\ndata: ${JSON.stringify(events)}\n\n`;
        controller.enqueue(encoder.encode(payload));
      } catch (error) {
        console.error('[activity-sse] Failed to send initial events:', error);
      }

      // Heartbeat every 30s to keep connection alive
      const heartbeat = setInterval(() => {
        try {
          controller.enqueue(encoder.encode(': heartbeat\n\n'));
        } catch {
          clearInterval(heartbeat);
        }
      }, 30000);

      // Cleanup on abort
      request.signal.addEventListener('abort', () => {
        clearInterval(heartbeat);
        if (clientId) removeClient(clientId);
        try {
          controller.close();
        } catch {}
      });
    },
    cancel() {
      if (clientId) removeClient(clientId);
    },
  });

  return new Response(readable, {
    headers: {
      'Content-Type': 'text/event-stream',
      'Cache-Control': 'no-cache, no-transform',
      Connection: 'keep-alive',
      'X-Accel-Buffering': 'no',
    },
  });
}
