import { getSessionUser } from "@/lib/auth";
import { subscribeMailboxLiveByEmail, type MailboxRealtimeEvent } from "@/lib/mailbox-live";
import {
  subscribeMailboxAutoSendNotificationsByOwnerEmail,
  type MailboxAutoSendCompletedEvent,
} from "@/lib/mailbox-notifications";

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

function encodeSseEvent(event: string, payload?: Record<string, unknown>) {
  const body = payload ? `data: ${JSON.stringify(payload)}\n` : "";
  return `event: ${event}\n${body}\n`;
}

export async function GET(request: Request) {
  const user = await getSessionUser();

  if (!user) {
    return new Response("unauthorized", { status: 401 });
  }

  const autoSendOnly = new URL(request.url).searchParams.get("events") === "auto-send";
  const encoder = new TextEncoder();
  let cleanup = () => {};

  const stream = new ReadableStream<Uint8Array>({
    start(controller) {
      let closed = false;

      const send = (event: string, payload?: Record<string, unknown>) => {
        if (closed) {
          return;
        }

        controller.enqueue(encoder.encode(encodeSseEvent(event, payload)));
      };

      const close = () => {
        if (closed) {
          return;
        }

        closed = true;
        cleanup();

        try {
          controller.close();
        } catch {
          // Ignore duplicate close attempts from abort/cancel races.
        }
      };

      const unsubscribeMailbox = autoSendOnly
        ? () => {}
        : subscribeMailboxLiveByEmail(user.email, (event: MailboxRealtimeEvent) => {
            switch (event.type) {
              case "ready":
                send("ready", event);
                break;
              case "mailbox-updated":
                send("mailbox-updated", event);
                break;
              case "error":
                send("mailbox-error", event);
                break;
            }
          });
      const unsubscribeAutoSend = subscribeMailboxAutoSendNotificationsByOwnerEmail(
        user.email,
        (event: MailboxAutoSendCompletedEvent) => {
          send("auto-send-completed", event);
        },
      );
      const heartbeatTimer = setInterval(() => {
        if (closed) {
          return;
        }

        controller.enqueue(encoder.encode(": keepalive\n\n"));
      }, 15_000);

      cleanup = () => {
        clearInterval(heartbeatTimer);
        unsubscribeMailbox();
        unsubscribeAutoSend();
      };

      request.signal.addEventListener("abort", close, { once: true });

      controller.enqueue(encoder.encode("retry: 3000\n\n"));
      send("ready", {
        at: new Date().toISOString(),
        mailbox: user.email,
      });
    },
    cancel() {
      cleanup();
    },
  });

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