import { createFileRoute } from "@tanstack/react-router";
import { superTokensRequestMiddleware } from "@/utils/supertokens";
import { pbAdmin } from "@/lib/pocketbase/client";
import { logger } from "@/lib/logger";

const json = (body: unknown, status = 200) =>
  new Response(JSON.stringify(body), {
    status,
    headers: { "Content-Type": "application/json" },
  });

export const Route = createFileRoute("/api/push/subscribe")({
  server: {
    middleware: [superTokensRequestMiddleware],
    handlers: {
      POST: async ({ request, context }) => {
        const player = (context as any).player;
        if (!player) return json({ error: "No player for session" }, 401);

        let payload: any;
        try {
          payload = await request.json();
        } catch {
          return json({ error: "Invalid JSON" }, 400);
        }

        const sub = payload?.subscription ?? payload;
        const endpoint: string | undefined = sub?.endpoint;
        const p256dh: string | undefined = sub?.keys?.p256dh;
        const auth: string | undefined = sub?.keys?.auth;

        if (!endpoint || !p256dh || !auth) {
          return json({ error: "Invalid subscription" }, 400);
        }

        try {
          await pbAdmin.upsertPushSubscription({
            player: player.id,
            endpoint,
            p256dh,
            auth,
            user_agent: request.headers.get("user-agent") ?? undefined,
          });
          return json({ ok: true });
        } catch (error) {
          logger.error("Push | subscribe failed", error);
          return json({ error: "Failed to store subscription" }, 500);
        }
      },
    },
  },
});
