import { createFileRoute } from "@tanstack/react-router";
import { msg } from "@lingui/core/macro";
import { superTokensRequestMiddleware } from "@/utils/supertokens";
import { sendPushToPlayer } from "@/lib/push";
import { isPushConfigured } from "@/lib/config";
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/test")({
  server: {
    middleware: [superTokensRequestMiddleware],
    handlers: {
      POST: async ({ context }) => {
        const player = (context as any).player;
        if (!player) return json({ error: "No player for session" }, 401);

        if (!isPushConfigured()) {
          return json({ error: "Push is not configured on the server" }, 503);
        }

        try {
          const result = await sendPushToPlayer(player.id, {
            title: "Flexxon",
            body: msg`Test notification — push is working on this device.`,
            url: "/settings",
            tag: "flexxon-test",
          });
          return json({ ok: true, ...result });
        } catch (error) {
          logger.error("Push | test send failed", error);
          return json({ error: "Failed to send test notification" }, 500);
        }
      },
    },
  },
});
