import { NextResponse } from "next/server";
import { isPaymentTestMode } from "../../../../lib/payments";
import { sendConfirmedPaymentEmail, type ConfirmPaymentOrderSnapshot } from "../../../../lib/payments/confirmPaymentEmail";
import { sendCriticalAlert } from "../../../../lib/alertAdmin";

const PAYLOAD_URL = process.env.PAYLOAD_URL || "https://payload.mk360.de";
const PAYMENT_WEBHOOK_SECRET = process.env.PAYMENT_WEBHOOK_SECRET || "";

// Test-mode stand-in for the real Stripe webhook — see
// spicy-leaping-pizza.md §7. Drives the exact same backend confirm-payment
// endpoint the real webhook calls, just without a real Stripe event/
// signature (there is none to verify in test mode). Hard-gated: must
// 404 whenever PAYMENT_TEST_MODE isn't explicitly on, so this can never
// become an unauthenticated "mark any order paid" endpoint in production.
export async function POST(request: Request) {
  if (!isPaymentTestMode) {
    return NextResponse.json({ ok: false }, { status: 404 });
  }

  const body = await request.json().catch(() => null);
  const orderId = body?.orderId;
  const providerReference = body?.providerReference;
  const paymentStatus = body?.paymentStatus === "failed" ? "failed" : "paid";
  if (!orderId || !providerReference) {
    return NextResponse.json({ ok: false, reason: "orderId und providerReference erforderlich." }, { status: 400 });
  }

  const res = await fetch(`${PAYLOAD_URL}/api/orders/${orderId}/confirm-payment`, {
    method: "POST",
    headers: {
      "x-payment-webhook-secret": PAYMENT_WEBHOOK_SECRET,
      "Content-Type": "application/json",
    },
    body: JSON.stringify({ paymentStatus, providerReference, paidAt: new Date().toISOString() }),
  }).catch((err) => {
    sendCriticalAlert("Test-confirm-Aufruf ans Backend fehlgeschlagen", { orderId, providerReference, error: String(err) });
    return null;
  });

  if (!res || !res.ok) {
    return NextResponse.json({ ok: false, reason: "Backend hat die Testzahlung nicht bestätigt." }, { status: 502 });
  }

  const data: { ok: boolean; alreadyProcessed?: boolean; order?: ConfirmPaymentOrderSnapshot } = await res.json();

  // Same email-send as the real webhook route — see its own comment and
  // confirmPaymentEmail.ts. Reproduces today's "immediate confirmation"
  // behavior on a test click, exercising the real send path rather than a
  // separate short-circuit.
  if (data.order && !data.alreadyProcessed) {
    void sendConfirmedPaymentEmail(data.order);
  }

  return NextResponse.json({ ok: true });
}
