import { sendOrderConfirmationEmail, sendPaymentSwitchedEmail, type OrderConfirmationEmailData } from "../orderEmail";
import { sendCriticalAlert } from "../alertAdmin";

// The `order` snapshot returned by the backend's confirm-payment endpoint
// (see docker/payload's src/lib/endpoints/confirmPayment.ts) — matches
// OrderConfirmationEmailData minus `customerEmail`, which is passed
// separately to sendOrderConfirmationEmail. Backend has no SMTP-based
// order-confirmation sender of its own (only the 4 status-change
// templates), so it returns everything needed here instead of the
// frontend needing an authenticated order-read path it doesn't otherwise
// have (ORDER_SERVICE_SECRET only ever authorizes *creating* an order).
export type ConfirmPaymentOrderSnapshot = OrderConfirmationEmailData & {
  customerEmail: string;
  // Present only when this payment came from switchPaymentToStripe.ts (an
  // existing Überweisung order moved to Stripe) — see this function's own
  // branch below.
  paymentSwitchedAt?: string;
};

// Called from both the real Stripe webhook route and its PAYMENT_TEST_MODE
// test-confirm sibling, right after confirm-payment reports success (and
// NOT `alreadyProcessed: true` — a repeat delivery must never resend
// this). Mirrors exactly what app/api/checkout/route.ts already does for
// a manual/Überweisung order today, just triggered from the payment
// webhook instead of the checkout request itself for gated methods.
//
// A payment-method switch (paymentSwitchedAt set) sends a short dedicated
// "Zahlung erhalten" confirmation instead — the customer already got the
// full order-confirmation email (with its invoice) when they originally
// placed the Überweisung order; resending that same email here would read
// as a second, brand-new purchase.
export async function sendConfirmedPaymentEmail(order: ConfirmPaymentOrderSnapshot): Promise<void> {
  const { customerEmail, ...emailData } = order;
  try {
    if (order.paymentSwitchedAt) {
      await sendPaymentSwitchedEmail(emailData, customerEmail);
    } else {
      await sendOrderConfirmationEmail(emailData, customerEmail);
    }
  } catch (err) {
    sendCriticalAlert("Bestätigungs-Mail konnte nach Zahlungsbestätigung nicht gesendet werden", {
      orderNumber: order.orderNumber,
      customerEmail,
      error: String(err),
    });
  }
}
