import { auth } from '@/lib/auth';
import { addClient, removeClient } from '@/lib/notification';
import { createFileRoute } from '@tanstack/react-router';
import { getRequestHeaders } from '@tanstack/react-start/server';

export const Route = createFileRoute('/api/notify')({
  server: {
    handlers: {
      GET: async ({ request }) => {
        const headers = getRequestHeaders();
        const session = await auth.api.getSession({ headers });

        if (!session?.session.userId) {
          return new Response('Unauthorized', { status: 401 });
        }

        const clientId = session.session.userId;

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

            controller.enqueue(
              `data: ${JSON.stringify({ type: `connected` })}\n\n`,
            );

            const heartbeat = setInterval(() => {
              controller.enqueue(`: keepalive\n\n`);
            }, 20000);

            request.signal.addEventListener('abort', () => {
              clearInterval(heartbeat);
              removeClient(clientId, controller);
            });
          },
        });

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