/**
 * Answering HBank's callback: right before charging a customer, HBank POSTs the payment to its `callback_url` and
 * charges only if you answer 200 with `{"resume": true}` as application/json within 10 seconds.
 *
 * It's signed: check the `HBank-Signature` header with your business's signing secret (business settings → Callback
 * URLs) before you approve: `verifySignature`, or pass `{ secret }` to the handlers below. Also check that `id` and
 * `amount` match an order you created, and confirm with `getPayment` before handing out goods.
 */
import { HBankError } from "./errors.js";

export interface Callback {
  /** The transaction id you got from createPayment: a random string like "tx_8fK2mQ7xRb4Tn9WcYz3LpH6v". */
  id: string;
  amount: number;
  currency: string;
  status: string;
  description: string;
}

export type CallbackAnswer = { resume: true } | { resume: false; error?: string };

/** What your handler decides: `true` to charge, `false` or a string (shown to the customer) to refuse. */
export type CallbackDecision = boolean | string | CallbackAnswer;
export type CallbackDecider = (callback: Callback) => CallbackDecision | Promise<CallbackDecision>;

/** Reads a callback body (parsed JSON or the raw text). Throws HBankError("invalid_callback") if it isn't one. */
export function parseCallback(body: unknown): Callback {
  let data = body;
  if (typeof data === "string") {
    try {
      data = JSON.parse(data);
    } catch {
      throw new HBankError("invalid_callback", undefined, "body is not JSON");
    }
  }
  const d = data as Record<string, unknown> | null;
  const id = typeof d?.id === "string" || typeof d?.id === "number" ? String(d.id) : "";
  const amount = Number(d?.amount);
  if (!d || typeof d !== "object" || id === "" || !Number.isFinite(amount) || typeof d.currency !== "string")
    throw new HBankError("invalid_callback", undefined, "missing or invalid id, amount or currency");
  return { id, amount, currency: d.currency, status: String(d.status ?? ""), description: String(d.description ?? "") };
}

export interface VerifyOptions {
  /** How old the signature may be, in seconds (default 300). */
  toleranceSeconds?: number;
  /** "Now" in Unix seconds (for tests). */
  now?: number;
}

/**
 * Whether `header` (the request's `HBank-Signature`: `t=<unix time>,v1=<hex>`) signs `body` (the raw request body,
 * exactly as received) with `secret`, and isn't older than the tolerance. Uses Web Crypto, so it works in Node 18+,
 * Deno, Bun, Workers and browsers alike.
 */
export async function verifySignature(secret: string, header: string | null | undefined, body: string | Uint8Array, options: VerifyOptions = {}): Promise<boolean> {
  if (!secret || !header) return false;
  const parts = Object.fromEntries(header.split(",").map((p) => p.split("=", 2)).filter((p) => p.length === 2));
  const t = Number(parts.t);
  if (!/^\d+$/.test(parts.t ?? "") || !Number.isSafeInteger(t)) return false;
  const now = options.now ?? Math.floor(Date.now() / 1000);
  if (Math.abs(now - t) > (options.toleranceSeconds ?? 300)) return false;
  const encoder = new TextEncoder();
  const key = await crypto.subtle.importKey("raw", encoder.encode(secret), { name: "HMAC", hash: "SHA-256" }, false, ["sign"]);
  const raw = typeof body === "string" ? encoder.encode(body) : body;
  const signed = new Uint8Array(raw.length + String(t).length + 1);
  signed.set(encoder.encode(`${t}.`));
  signed.set(raw, String(t).length + 1);
  const mac = new Uint8Array(await crypto.subtle.sign("HMAC", key, signed));
  const expected = Array.from(mac, (b) => b.toString(16).padStart(2, "0")).join("");
  const given = String(parts.v1 ?? "");
  // Constant time: every character is compared.
  let diff = given.length ^ expected.length;
  for (let i = 0; i < expected.length; i++) diff |= expected.charCodeAt(i) ^ given.charCodeAt(i);
  return diff === 0;
}

/** Options for the ready-made handlers. */
export interface HandlerOptions {
  /** Your signing secret: callbacks without a valid HBank-Signature are refused ("Invalid callback"). */
  secret?: string;
}

/** The answer that lets HBank charge the customer. */
export const approve = (): CallbackAnswer => ({ resume: true });

/** The answer that refuses the payment; the customer sees `error`. */
export const refuse = (error?: string): CallbackAnswer => (error ? { resume: false, error } : { resume: false });

function answerFor(decision: CallbackDecision): CallbackAnswer {
  if (decision === true) return approve();
  if (decision === false) return refuse();
  if (typeof decision === "string") return refuse(decision);
  return decision;
}

/**
 * A callback endpoint for frameworks built on the Fetch API's Request/Response: Next.js route handlers, Hono, Remix,
 * SvelteKit, Astro, Bun, Deno, Cloudflare Workers.
 *
 * ```ts
 * // app/hbank/callback/route.ts (Next.js)
 * export const POST = callbackHandler(async (cb) => {
 *   const order = await db.orders.findByTransaction(cb.id);
 *   return order && order.total === cb.amount ? true : "This order is no longer available";
 * });
 * ```
 */
export function callbackHandler(decide: CallbackDecider, options: HandlerOptions = {}): (request: Request) => Promise<Response> {
  return async (request) => {
    let answer: CallbackAnswer;
    try {
      const raw = await request.text();
      if (options.secret !== undefined && !(await verifySignature(options.secret, request.headers.get("HBank-Signature"), raw)))
        throw new HBankError("invalid_callback", undefined, "bad or missing HBank-Signature");
      answer = answerFor(await decide(parseCallback(raw)));
    } catch (e) {
      answer = refuse(e instanceof HBankError && e.code === "invalid_callback" ? "Invalid callback" : "The shop couldn't confirm this order");
    }
    return new Response(JSON.stringify(answer), { status: 200, headers: { "Content-Type": "application/json" } });
  };
}

interface ExpressLikeRequest { body?: unknown; rawBody?: string | Uint8Array; get?(name: string): string | undefined; headers?: Record<string, unknown> }
interface ExpressLikeResponse { status(code: number): ExpressLikeResponse; json(body: unknown): unknown }

/**
 * A callback endpoint for Express (and Express-style frameworks: Fastify via `reply`, Koa adapters aside).
 * Needs a JSON body parser, e.g. `app.use(express.json())`. With `{ secret }`, the signature is checked against the raw
 * body, so keep it: `express.json({ verify: (req, _res, buf) => { req.rawBody = buf; } })`.
 *
 * ```ts
 * const json = express.json({ verify: (req, _res, buf) => { req.rawBody = buf; } });
 * app.post("/hbank/callback", json, expressCallback(async (cb) => orders.matches(cb.id, cb.amount), { secret: process.env.HBANK_CALLBACK_SECRET }));
 * ```
 */
export function expressCallback(decide: CallbackDecider, options: HandlerOptions = {}) {
  return async (req: ExpressLikeRequest, res: ExpressLikeResponse): Promise<void> => {
    let answer: CallbackAnswer;
    try {
      if (options.secret !== undefined) {
        const header = req.get?.("HBank-Signature") ?? (req.headers?.["hbank-signature"] as string | undefined);
        if (req.rawBody === undefined || !(await verifySignature(options.secret, header, req.rawBody)))
          throw new HBankError("invalid_callback", undefined, "bad or missing HBank-Signature (is rawBody kept?)");
      }
      answer = answerFor(await decide(parseCallback(req.body)));
    } catch (e) {
      answer = refuse(e instanceof HBankError && e.code === "invalid_callback" ? "Invalid callback" : "The shop couldn't confirm this order");
    }
    res.status(200).json(answer);
  };
}
