import type { LearnServePaymentStatusRecord } from "./services/learnServe";

/**
 * Upay's return pages (`/payment/result`, `/payment/cancelled`).
 *
 * Upay appends its own query (`payment_id`, `result`, `track_id`, `ref`,
 * `requested_order_id`, …). Only `requested_order_id` is read — it is our
 * order reference — and the outcome always comes from
 * `POST /payments/{reference}/verify/`, never from Upay's `result`.
 */

/** The reference to verify, or null when the query does not carry a usable one. */
export function paymentReferenceFromQuery(query: { get(name: string): string | null }): string | null {
  const reference = query.get("requested_order_id")?.trim() ?? "";
  return /^[A-Za-z0-9._-]{1,128}$/.test(reference) ? reference : null;
}

export type PaymentReturnState = "pending" | "paid" | "refunding" | "refunded" | "unpaid";

/** Only the verified reason can call an unsuccessful payment a user cancel. */
export function failedPaymentTitleKey(outcome: string | null | undefined): string {
  return outcome === "participant_cancelled" ? "COMMON.PAYMENT_CANCELLED_TITLE" : "COMMON.PAYMENT_NOT_COMPLETED";
}

/** The message key of each verified state when the page is not polling. */
const STATE_TITLE_KEYS: Record<Exclude<PaymentReturnState, "unpaid">, string> = {
  pending: "COMMON.PAYMENT_STILL_PENDING",
  paid: "COMMON.PAYMENT_SUCCESS",
  refunding: "COMMON.REFUND_IN_PROGRESS",
  refunded: "COMMON.REFUND_COMPLETED",
};

/**
 * The heading of the return page. It is decided by the verified state and the
 * verified `outcome` only. The route the payer came back to (`/payment/cancelled`
 * vs `/payment/result`) and Upay's own query text never pick the wording: a
 * declined card also lands on the cancel URL, and only the backend knows that
 * the payer really cancelled.
 */
export function paymentReturnTitleKey(state: PaymentReturnState, polling: boolean, outcome: string | null | undefined): string {
  if (state === "unpaid") return failedPaymentTitleKey(outcome);
  return polling ? "COMMON.PAYMENT_CHECKING" : STATE_TITLE_KEYS[state];
}

/**
 * What the page says. A captured payment that is being returned (a late
 * capture after the seat went, a cancelled course) reads as a refund, not as a
 * failure: the money was taken and is on its way back (PDF p.20).
 */
export function paymentReturnState(record: LearnServePaymentStatusRecord | null | undefined): PaymentReturnState | null {
  if (!record) return null;
  const refund = record.refund?.status;
  if (record.payment_status === "refunded" || record.payment_status === "partially_refunded" || refund === "succeeded") return "refunded";
  if (record.refund && refund !== "succeeded") return "refunding";
  if (record.payment_status === "paid") return "paid";
  if (record.payment_status === "pending") return "pending";
  return "unpaid";
}

/** Poll every 5 s while pending: 12 calls a minute is the route's throttle. */
export const PAYMENT_POLL_INTERVAL_MS = 5000;
/** Then stop and say the confirmation will arrive by itself (the webhook decides too). */
export const PAYMENT_POLL_MAX_ATTEMPTS = 10;

export function shouldPollPayment(state: PaymentReturnState | null, attempts: number): boolean {
  return state === "pending" && attempts < PAYMENT_POLL_MAX_ATTEMPTS;
}

/** The same checkout, while the server still offers it. */
export function resumableCheckoutUrl(record: LearnServePaymentStatusRecord | null | undefined): string | null {
  const url = record?.resumable === true ? record.gateway_checkout_url : null;
  return typeof url === "string" && /^https:\/\//.test(url) ? url : null;
}
