import { describe, expect, it, vi } from "vitest";

import {
  getPaymentUrl,
  getStripeClientSecret,
  isEzpayPayment,
  launchEzpayRedirect,
} from "../payment_launch";

describe("payment launch helpers", () => {
  it("extracts supported redirect urls from payment params", () => {
    expect(getPaymentUrl({ cashier_url: "https://pay.example/cashier" })).toBe(
      "https://pay.example/cashier",
    );
    expect(getPaymentUrl({ checkoutUrl: "https://pay.example/checkout" })).toBe(
      "https://pay.example/checkout",
    );
    expect(getPaymentUrl({ url: "" })).toBeNull();
  });

  it("detects ezpay provider case-insensitively", () => {
    expect(isEzpayPayment({ provider: "ezpay" })).toBe(true);
    expect(isEzpayPayment({ provider: "EZPAY" })).toBe(true);
    expect(isEzpayPayment({ provider: "stripe" })).toBe(false);
  });

  it("extracts stripe client secrets only for stripe-like providers", () => {
    expect(
      getStripeClientSecret({
        provider: "stripe",
        clientSecret: "pi_secret",
      }),
    ).toBe("pi_secret");
    expect(getStripeClientSecret({ client_secret: "pi_secret_snake" })).toBe(
      "pi_secret_snake",
    );
    expect(
      getStripeClientSecret({
        provider: "ezpay",
        clientSecret: "pi_secret",
      }),
    ).toBeNull();
  });

  it("reports a launch failure before redirecting without an order id", async () => {
    const onOpened = vi.fn();
    const onFailed = vi.fn();

    await launchEzpayRedirect({
      orderId: null,
      paymentUrl: "https://pay.example/checkout?token=secret",
      subscriptionType: "topup",
      onOpened,
      onFailed,
    });

    expect(onOpened).not.toHaveBeenCalled();
    expect(onFailed).toHaveBeenCalledWith(
      "Missing order id before opening Ezpay.",
    );
  });
});
