import { getServerSession } from 'next-auth';
import { authOptions } from '@/lib/auth';
import { addClient, removeClient } from '@/lib/sse';

export const dynamic = 'force-dynamic';
export const runtime = 'nodejs';

export async function GET() {
    const session = await getServerSession(authOptions);
    const userId = (session?.user as any)?.id;
    if (!userId) {
        return new Response('Unauthorized', { status: 401 });
    }

    const encoder = new TextEncoder();
    let sseClient: ReturnType<typeof addClient> | null = null;
    let heartbeatInterval: NodeJS.Timeout | null = null;

    const stream = new ReadableStream({
        start(controller) {
            sseClient = addClient(userId, controller);

            // Send initial connected event
            controller.enqueue(encoder.encode(`event: connected\ndata: ${JSON.stringify({ clientId: sseClient.id })}\n\n`));

            // Heartbeat every 30s to keep connection alive
            heartbeatInterval = setInterval(() => {
                try {
                    controller.enqueue(encoder.encode(`: heartbeat\n\n`));
                } catch {
                    if (heartbeatInterval) clearInterval(heartbeatInterval);
                    if (sseClient) removeClient(sseClient);
                }
            }, 30000);
        },
        cancel() {
            if (heartbeatInterval) clearInterval(heartbeatInterval);
            if (sseClient) removeClient(sseClient);
        },
    });

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