/**
 * BE-125 — reading a paid registration's reply.
 *
 * The defect these exist for: `POST /learn-serve-opportunity-registrations/`
 * answers `{ registration, transaction }` for a paid opportunity and a plain
 * registration for a free one, and the screens ignored the body entirely —
 * so a payer was told «تم التسجيل بنجاح», routed to the thank-you page, and
 * never sent to the gateway, while the seat was held for two hours.
 */
import assert from "node:assert/strict";
import { describe, test } from "node:test";

import {
  checkoutFromRegistration,
  formatAmount,
  isPaidRegistrationResponse,
  toAmount,
  type RegistrationResponseRecord,
  type TransactionRecord,
} from "@/features/opportunities/payment";
import type { ApiResponse } from "@/lib/api/types";

const transaction = (
  overrides: Partial<TransactionRecord> = {}
): TransactionRecord => ({
  id: 3,
  opportunity_id: 11,
  registration_id: 42,
  gross_amount: "25.00",
  platform_fee_percentage: "7.00",
  platform_fee_amount: "1.75",
  gateway_fee_amount: null,
  net_amount: null,
  currency: "KWD",
  status: "pending",
  gateway: "upay",
  gateway_checkout_url: "https://pay.example.test/checkout/abc",
  initiated_at: "2026-10-04T09:00:00+03:00",
  paid_at: null,
  refunded_at: null,
  ...overrides,
});

const envelope = (data: unknown): ApiResponse<RegistrationResponseRecord> =>
  ({
    key: "success",
    msg: "Registration created — complete payment to confirm your spot.",
    code: 201,
    response_status: { error: false, validation_errors: [] },
    data,
  }) as unknown as ApiResponse<RegistrationResponseRecord>;

/** The free branch: the registration record itself, with no nesting. */
const freeRegistration = envelope({ id: 42, opportunity_id: 11, user_id: 7 });

describe("checkoutFromRegistration", () => {
  test("the paid branch yields the transaction to pay", () => {
    const paid = envelope({ registration: { id: 42 }, transaction: transaction() });
    assert.equal(
      checkoutFromRegistration(paid)?.gateway_checkout_url,
      "https://pay.example.test/checkout/abc"
    );
  });

  test("a free registration yields nothing to pay", () => {
    assert.equal(checkoutFromRegistration(freeRegistration), null);
  });

  /*
   * A paid branch whose gateway refused to start. There is nowhere to send
   * the payer, and treating it as a success is the original defect — the
   * caller reports it instead.
   */
  test("a transaction with no checkout url is not a checkout", () => {
    const noUrl = envelope({
      registration: { id: 42 },
      transaction: transaction({ gateway_checkout_url: null }),
    });
    assert.equal(checkoutFromRegistration(noUrl), null);
    assert.equal(isPaidRegistrationResponse(noUrl), true);

    const blank = envelope({
      registration: { id: 42 },
      transaction: transaction({ gateway_checkout_url: "" }),
    });
    assert.equal(checkoutFromRegistration(blank), null);
  });

  test("an empty or missing envelope is handled", () => {
    assert.equal(checkoutFromRegistration(null), null);
    assert.equal(checkoutFromRegistration(undefined), null);
    assert.equal(checkoutFromRegistration(envelope(null)), null);
  });

  test("the two branches are told apart", () => {
    assert.equal(isPaidRegistrationResponse(freeRegistration), false);
    assert.equal(
      isPaidRegistrationResponse(
        envelope({ registration: { id: 42 }, transaction: transaction() })
      ),
      true
    );
  });
});

describe("money formatting", () => {
  /* The API sends decimals as strings on some endpoints and numbers on
     others; both are the same amount. */
  test("a string amount and a number amount agree", () => {
    assert.equal(toAmount("25.00"), 25);
    assert.equal(toAmount(25), 25);
    assert.equal(formatAmount("25", "KWD"), "25.000 KWD");
    assert.equal(formatAmount(25, "KWD"), "25.000 KWD");
  });

  /* Preserve fils returned by the reviewed three-decimal KWD contract. */
  test("it preserves the three-decimal Kuwaiti dinar precision", () => {
    assert.equal(formatAmount(12.5), "12.500");
    assert.equal(formatAmount("7.456"), "7.456");
  });

  test("an absent or unreadable amount is absent, not zero", () => {
    assert.equal(formatAmount(null), null);
    assert.equal(formatAmount(undefined), null);
    assert.equal(formatAmount(""), null);
    assert.equal(formatAmount("not a number"), null);
    assert.equal(toAmount(null), null);
  });

  test("zero is an amount, not an absence", () => {
    assert.equal(toAmount(0), 0);
    assert.equal(formatAmount(0, "KWD"), "0.000 KWD");
  });
});
