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/unsubscribe")({
  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 endpoint: string | undefined =
          payload?.endpoint ?? payload?.subscription?.endpoint;
        if (!endpoint) return json({ error: "Missing endpoint" }, 400);

        try {
          await pbAdmin.deletePushSubscriptionByEndpoint(endpoint);
          return json({ ok: true });
        } catch (error) {
          logger.error("Push | unsubscribe failed", error);
          return json({ error: "Failed to remove subscription" }, 500);
        }
      },
    },
  },
});
