import { createFileRoute } from "@tanstack/react-router";

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

export const Route = createFileRoute("/api/printpay/status")({
  server: {
    handlers: {
      POST: async ({ request }) => {
        try {
          const auth = request.headers.get("authorization") ?? "";
          const token = auth.startsWith("Bearer ") ? auth.slice(7) : "";
          if (!token) return json({ error: "Unauthorized" }, 401);

          const body = (await request.json().catch(() => ({}))) as { deposit_id?: string };
          const depositId = String(body.deposit_id ?? "");
          if (!depositId) return json({ error: "Missing deposit" }, 400);

          const { supabaseAdmin } = await import("@/integrations/supabase/client.server");
          const { data: userRes, error: userErr } = await supabaseAdmin.auth.getUser(token);
          if (userErr || !userRes.user) return json({ error: "Unauthorized" }, 401);

          const { data: dep } = await supabaseAdmin
            .from("deposits")
            .select("id, user_id, amount, status, paystack_reference")
            .eq("id", depositId)
            .maybeSingle();
          if (!dep || dep.user_id !== userRes.user.id) return json({ error: "Deposit not found" }, 404);
          if (dep.status === "approved") return json({ status: "SUCCESS" });
          if (dep.status === "rejected") return json({ status: "FAILED", message: "Payment was not completed" });
          if (!dep.paystack_reference) return json({ status: "PENDING" });

          const res = await fetch(
            `https://printpay.site/api/stk_push?check_status=${encodeURIComponent(dep.paystack_reference)}`,
          );
          const raw = await res.text();
          let payload: { status?: string; amount?: string | number; mpesa_receipt_number?: string | null } = {};
          try {
            payload = JSON.parse(raw);
          } catch {
            return json({ status: "PENDING" });
          }

          const state = String(payload.status ?? "").toUpperCase();
          if (state !== "SUCCESS") {
            if (state === "FAILED" || state === "CANCELLED") {
              await supabaseAdmin
                .from("deposits")
                .update({ status: "rejected", admin_notes: "Payment not completed on the M-PESA prompt" })
                .eq("id", dep.id)
                .eq("status", "pending");
              return json({ status: "FAILED", message: "Payment was cancelled or failed" });
            }
            return json({ status: "PENDING" });
          }

          const paid = Number(payload.amount ?? 0);
          if (Math.round(paid * 100) !== Math.round(Number(dep.amount) * 100)) {
            return json({ status: "FAILED", message: "Amount mismatch — contact support" });
          }

          const { error: rpcErr } = await supabaseAdmin.rpc("credit_deposit_gateway", {
            _deposit_id: dep.id,
            _reference: payload.mpesa_receipt_number ?? dep.paystack_reference,
            _provider: "printpay",
          });
          if (rpcErr) return json({ status: "FAILED", message: rpcErr.message });
          return json({ status: "SUCCESS" });
        } catch (e) {
          return json({ error: e instanceof Error ? e.message : "Unexpected error" }, 500);
        }
      },
    },
  },
});
