import type { ApiResponse } from "@/lib/api/types";
import type { LearnServeRegistrationRecord } from "@/features/opportunities/permissionRecord";

/**
 * BE-125 — paying for a development opportunity.
 *
 * The shape of the flow, because it decides everything the screens do:
 *
 * 1. Registering for a **paid** opportunity creates the registration row
 *    immediately, `status: pending` and `payment_status: pending`, and hands
 *    back a checkout URL. The row does **not** hold a seat (BE-231, PDF p.20):
 *    the last seat goes to the first completed payment, checked under lock
 *    when the payment is confirmed; a later capture is refunded in full.
 * 2. Upay sends the payer back to `/payment/result` (or `/payment/cancelled`)
 *    with our reference in `requested_order_id`; that page asks
 *    `POST /payments/{reference}/verify/` for the real outcome and offers the
 *    same checkout again while it is still `resumable` (`paymentReturn.ts`).
 * 3. An unpaid checkout is cancelled by the backend after
 *    `ABANDONED_CHECKOUT_TTL_HOURS` (5 minutes).
 *
 * Two consequences the UI has to live with, rather than pretend away:
 *
 * - Sending the payer to the gateway is a **full navigation**, not a toast and
 *   a thank-you page. Before this existed the screen reported "registered"
 *   and dropped the URL on the floor, so the seat was held and nobody ever
 *   paid.
 * - An unpaid attempt is not a booking (PDF p.13: the button reads «حجز»
 *   again). Pressing it re-posts the registration: the server hands back the
 *   same checkout while it is inside its five minutes, or opens a fresh one
 *   (`LearnServeRegistrationController::createRegistration`). The return page
 *   offers the same checkout while `resumable` is true.
 */

/** `PaymentStatus` on the API. */
export type PaymentStatus =
  | "pending"
  | "paid"
  | "refunded"
  | "partially_refunded"
  | "failed"
  | "canceled";

/** How long the seat is held before the backend cancels an unpaid checkout. */
export const ABANDONED_CHECKOUT_TTL_HOURS = 5 / 60;

/** `TransactionResource`. Money fields are numbers; the API does not localize them. */
export interface TransactionRecord {
  id: number;
  opportunity_id: number;
  registration_id: number;
  gross_amount: number | string | null;
  platform_fee_percentage: number | string | null;
  platform_fee_amount: number | string | null;
  gateway_fee_amount: number | string | null;
  net_amount: number | string | null;
  currency: string | null;
  status: PaymentStatus | null;
  gateway: string | null;
  /** Where the payer must be sent. Null if the gateway refused to start. */
  gateway_checkout_url: string | null;
  initiated_at: string | null;
  paid_at: string | null;
  refunded_at: string | null;
}

/** What `POST /learn-serve-opportunity-registrations/` answers for a paid one. */
export interface PaidRegistrationRecord {
  registration: LearnServeRegistrationRecord;
  transaction: TransactionRecord;
}

/** Either shape, since the endpoint picks by `opportunity.is_paid`. */
export type RegistrationResponseRecord =
  | LearnServeRegistrationRecord
  | PaidRegistrationRecord;

/**
 * The checkout to send the payer to, or `null` when this was a free
 * registration and the normal thank-you path applies.
 *
 * Keyed on the nesting rather than on the opportunity's `is_paid`: the server
 * decides which branch it took, and reading its answer means a free
 * opportunity someone marked paid mid-flight cannot strand the payer.
 */
export function checkoutFromRegistration(
  envelope: ApiResponse<RegistrationResponseRecord> | null | undefined
): TransactionRecord | null {
  const body = envelope?.data as PaidRegistrationRecord | undefined;
  const transaction = body?.transaction;
  if (!transaction || typeof transaction !== "object") return null;
  const url = transaction.gateway_checkout_url;
  /* A transaction with no URL is a gateway that refused to start. There is
     nothing to navigate to, and saying "registered" would be the old bug
     again — the caller reports it as a failure instead. */
  return typeof url === "string" && url !== "" ? transaction : null;
}

/**
 * True when the reply was the paid branch at all, whether or not a URL came
 * with it — which is how the caller tells "no payment needed" apart from
 * "payment needed and we cannot start it".
 */
export function isPaidRegistrationResponse(
  envelope: ApiResponse<RegistrationResponseRecord> | null | undefined
): boolean {
  const body = envelope?.data as PaidRegistrationRecord | undefined;
  return Boolean(body && typeof body === "object" && "transaction" in body);
}

/**
 * Hand the browser to the gateway.
 *
 * `assign`, not `replace`: Back should return to the opportunity, which is
 * where an abandoned payment leaves the reader. A plain navigation rather
 * than a new tab, because a hosted checkout is the whole page it runs in and
 * a popup is the first thing a browser blocks.
 *
 * Wrapped so the one place that leaves the app is greppable, and so tests can
 * assert the destination without a jsdom navigation.
 */
export function goToCheckout(url: string): void {
  window.location.assign(url);
}

/** A money amount as the API sends it — `"12.50"` or `12.5` — as a number. */
export function toAmount(value: number | string | null | undefined): number | null {
  if (value === null || value === undefined || value === "") return null;
  const amount = typeof value === "number" ? value : Number(value);
  return Number.isFinite(amount) ? amount : null;
}

/** KWD retains three decimal places, including the 0.200 cancellation fee. */
export function formatAmount(
  value: number | string | null | undefined,
  currency?: string | null
): string | null {
  const amount = toAmount(value);
  if (amount === null) return null;
  const isKwd = !currency || ["KWD", "KD", "د.ك"].includes(currency.toUpperCase());
  const text = amount.toFixed(isKwd ? 3 : 2);
  return currency ? `${text} ${currency}` : text;
}
