import { AuthenticationError, HBankConnectionError, HBankError } from "./errors.js";
import type {
  Amount, CreatePaymentParams, CreateSubscriptionParams, Payment, PaymentCode, Rate, RefundParams, RefundResult,
  Subscription, SubscriptionCheckout, SubscriptionCheckoutParams, SubscriptionsCheckout, SubscriptionsCheckoutParams,
} from "./types.js";

export const DEFAULT_BASE_URL = "https://bank.thehsi.cloud";

export interface HBankOptions {
  apiKey: string;
  /** Default: https://bank.thehsi.cloud */
  baseUrl?: string;
  /** Per request, in milliseconds. Default 30000. */
  timeoutMs?: number;
  /** A custom fetch (for tests, proxies or older runtimes). Default: the global fetch. */
  fetch?: typeof fetch;
}

type Json = Record<string, unknown>;

/**
 * Client for the HBank merchant API (v1). Server side only: it needs your secret API key.
 *
 * ```ts
 * const bank = new HBank({ apiKey: process.env.HBANK_API_KEY! });
 * const tid = await bank.createPayment({ amount: "24.90", currency: "EUR", callback_url: "https://shop.example/hbank/callback" });
 * res.redirect(bank.checkoutUrl(tid));
 * ```
 */
export class HBank {
  readonly baseUrl: string;
  private readonly apiKey: string;
  private readonly timeoutMs: number;
  private readonly fetchImpl: typeof fetch;

  constructor(options: HBankOptions) {
    if (!options?.apiKey) throw new TypeError("apiKey is required");
    this.apiKey = options.apiKey;
    this.baseUrl = (options.baseUrl ?? DEFAULT_BASE_URL).replace(/\/+$/, "");
    this.timeoutMs = options.timeoutMs ?? 30_000;
    const f = options.fetch ?? globalThis.fetch;
    if (typeof f !== "function") throw new TypeError("No fetch available: use Node 18+ or pass options.fetch");
    this.fetchImpl = f.bind(globalThis);
  }

  // ── Payments ─────────────────────────────────────────────

  /** Creates a pending payment request and returns its transaction id. It stays payable for one hour. */
  async createPayment(params: CreatePaymentParams): Promise<string> {
    const body = compact({ ...params, amount: amount(params.amount) });
    return (await this.post("payment/request", body)).transaction_id as string;
  }

  /** A QR code / link for a pending payment. Calling it again returns the same code. */
  async createPaymentCode(transactionId: string): Promise<PaymentCode> {
    const d = await this.post("payment/code", { transaction_id: transactionId });
    return { code: d.code as string, url: d.url as string, qr_svg: d.qr_svg as string };
  }

  /** The current state of one of your payments. Check `status === "completed"` here before handing out goods. */
  async getPayment(transactionId: string): Promise<Payment> {
    return (await this.post("payment/details", { transaction_id: transactionId })).transaction as Payment;
  }

  /**
   * Refunds (part of) a completed payment. Not safe to blindly retry after a timeout: check `refunded` with
   * `getPayment` first.
   */
  async refund(transactionId: string, params: RefundParams = {}): Promise<RefundResult> {
    const body = compact({ transaction_id: transactionId, amount: params.amount === undefined ? undefined : amount(params.amount), reason: params.reason });
    const d = await this.post("payment/refund", body);
    return { refund: d.refund, transaction: d.transaction } as RefundResult;
  }

  /** The hosted checkout (card number + PIN) for a payment. The payment needs a `callback_url`. */
  checkoutUrl(transactionId: string): string {
    return `${this.baseUrl}/api/payment?tid=${encodeURIComponent(String(transactionId))}`;
  }

  // ── Subscriptions ────────────────────────────────────────

  /** Offers a subscription. Send the customer its `url` (or show `qr_svg`). */
  async createSubscription(params: CreateSubscriptionParams): Promise<Subscription> {
    return (await this.post("subscriptions", offer(params))).subscription as Subscription;
  }

  /** Offers a subscription and creates its first payment, for the pay button / hosted checkout. */
  async createSubscriptionCheckout(params: SubscriptionCheckoutParams): Promise<SubscriptionCheckout> {
    const d = await this.post("subscriptions/checkout", compact({ ...offer(params), callback_url: params.callback_url }));
    return { transaction_id: d.transaction_id, subscription: d.subscription } as SubscriptionCheckout;
  }

  /**
   * One first payment for several subscriptions (up to 20, one currency): offer ids or new offers. Paying it starts them
   * all; after that each renews on its own. When one is refused, nothing is offered.
   */
  async createSubscriptionsCheckout(params: SubscriptionsCheckoutParams): Promise<SubscriptionsCheckout> {
    const items = params.subscriptions.map((item) => (typeof item === "string" ? item : offer(item)));
    const d = await this.post("subscriptions/checkout", compact({ subscriptions: items, description: params.description, callback_url: params.callback_url }));
    return { transaction_id: d.transaction_id, subscriptions: d.subscriptions } as SubscriptionsCheckout;
  }

  /** A new first payment for a subscription already offered (`not_open` once someone subscribed). */
  async checkoutSubscription(subscriptionId: string, params: { callback_url?: string } = {}): Promise<SubscriptionCheckout> {
    const d = await this.post(`subscriptions/${encodeURIComponent(subscriptionId)}/checkout`, compact({ callback_url: params.callback_url }));
    return { transaction_id: d.transaction_id, subscription: d.subscription } as SubscriptionCheckout;
  }

  /** Your subscriptions, newest first (up to 100). */
  async listSubscriptions(): Promise<Subscription[]> {
    return (await this.get("subscriptions")).subscriptions as Subscription[];
  }

  async getSubscription(subscriptionId: string): Promise<Subscription> {
    return (await this.get(`subscriptions/${encodeURIComponent(subscriptionId)}`)).subscription as Subscription;
  }

  /** No more charges. It stays in its `active_period` until `current_period_end`. */
  async cancelSubscription(subscriptionId: string): Promise<Subscription> {
    return (await this.post(`subscriptions/${encodeURIComponent(subscriptionId)}/cancel`, {})).subscription as Subscription;
  }

  // ── Currencies ───────────────────────────────────────────

  async convert(value: Amount, currencyFrom: string, currencyTo: string): Promise<number> {
    const d = await this.get("currency/convert", { amount: amount(value), currency_from: currencyFrom, currency_to: currencyTo });
    return d.amount as number;
  }

  async rate(currencyFrom: string, currencyTo: string): Promise<Rate> {
    const d = await this.get("currency/rate", { currency_from: currencyFrom, currency_to: currencyTo });
    return { to_rate: d.to_rate as number, from_rate: d.from_rate as number };
  }

  // ── Transport ────────────────────────────────────────────

  private get(path: string, query?: Record<string, string>): Promise<Json> {
    return this.send("GET", path + (query ? "?" + new URLSearchParams(query).toString() : ""));
  }

  private post(path: string, body: Json): Promise<Json> {
    return this.send("POST", path, JSON.stringify(body));
  }

  private async send(method: string, path: string, body?: string): Promise<Json> {
    const headers: Record<string, string> = { Authorization: `Bearer ${this.apiKey}`, Accept: "application/json" };
    if (body !== undefined) headers["Content-Type"] = "application/json";

    const controller = new AbortController();
    const timer = setTimeout(() => controller.abort(), this.timeoutMs);
    let status: number;
    let text: string;
    try {
      const res = await this.fetchImpl(`${this.baseUrl}/api/v1/${path}`, { method, headers, body, signal: controller.signal });
      status = res.status;
      text = await res.text();
    } catch (e) {
      if (controller.signal.aborted) throw new HBankConnectionError("timeout", `No answer within ${this.timeoutMs} ms`, e);
      throw new HBankConnectionError("connection_failed", e instanceof Error ? e.message : String(e), e);
    } finally {
      clearTimeout(timer);
    }

    if (status === 401) throw new AuthenticationError("missing_api_key", status, text.trim() || undefined);
    if (status === 403) throw new AuthenticationError("invalid_api_key", status, text.trim() || undefined);

    let data: unknown;
    try {
      data = JSON.parse(text);
    } catch {
      throw new HBankError("invalid_response", status, text.slice(0, 200) || undefined, text);
    }
    if (typeof data !== "object" || data === null || Array.isArray(data))
      throw new HBankError("invalid_response", status, text.slice(0, 200), data);
    const json = data as Json;
    if (status < 200 || status >= 300 || json.success === false) {
      const code = typeof json.error === "string" ? json.error : `http_${status}`;
      throw new HBankError(code, status, typeof json.message === "string" ? json.message : undefined, json);
    }
    return json;
  }
}

/** Sends amounts as strings so no digits are lost: 24.9 -> "24.9", "24.90" stays "24.90". */
function amount(value: Amount): string {
  if (typeof value === "number") {
    if (!Number.isFinite(value)) throw new TypeError("amount must be a finite number");
    return String(value);
  }
  if (typeof value === "string") return value.trim();
  throw new TypeError("amount must be a number or a numeric string");
}


function offer(p: CreateSubscriptionParams): Json {
  return compact({ amount: amount(p.amount), currency: p.currency, interval: p.interval, interval_count: p.interval_count ?? 1, description: p.description });
}

function compact(o: Record<string, unknown>): Json {
  return Object.fromEntries(Object.entries(o).filter(([, v]) => v !== undefined && v !== null));
}
