/**
 * Nod Pass SDK for TypeScript / JavaScript — no dependencies. Node 18+, Deno, Bun and browsers.
 *
 *   import { Nod, Refused } from "./nodpass.mjs";
 *   const nod = new Nod({ key: "stk_..." });                 // booking system key
 *   try {
 *     const receipt = await nod.authoriseBooking({ nodId, agent: "atlas", counterparty: "courier9",
 *       action: "book freight", amount: 3950, ref: "FX-2291" });
 *     // place the booking only after a receipt
 *   } catch (e) { if (e instanceof Refused) console.log("don't book:", e.message); else throw e; }
 *
 *   const event = await Nod.verifyWebhook(secret, rawBody, req.headers["nod-signature"]);
 *
 * Docs: https://nodpass.org/docs
 */
export const VERSION = "1.0.0";

export class NodError extends Error {
  constructor(public status: number, message: string) {
    super(message);
    this.name = "NodError";
  }
}
/** Nod's rules refused the action (HTTP 403). Do not proceed. */
export class Refused extends NodError {
  constructor(message: string) {
    super(403, message);
    this.name = "Refused";
  }
}

export interface Passport {
  agent_id: string;
  name: string;
  proof_of_authority: { acts_for: string; owner: string; owner_verified: boolean; verified_by: string | null; may: string[]; limit: number | null; currency: string };
  proof_of_performance: { confirmed_jobs: number; disputes: number; distinct_counterparties: number };
  trust: { independent_confirmations: number; independent_companies: number; trust_score: number; flags: string[] };
  [k: string]: unknown;
}
export interface NodRequest { nod_id: string; status: "pending" | "nodded" | "declined"; binding: string; auto_reason: string | null; expires: string }
export interface NodStatus { id: string; status: "pending" | "nodded" | "declined"; ref: string; counterparty: string; amount: number; currency: string; action: string; decided_by: string | null; auto: number; used: number; expires: string; binding: string }
export interface Receipt { action_id: string; receipt: string }
export interface WebhookEvent { id: string; type: string; created: string; data: Record<string, unknown> }

export interface NodOptions { key?: string; base?: string; timeoutMs?: number }

export class Nod {
  readonly key?: string;
  readonly base: string;
  readonly timeoutMs: number;

  constructor(opts: NodOptions = {}) {
    this.key = opts.key;
    this.base = (opts.base ?? "https://api.nodpass.org").replace(/\/+$/, "");
    this.timeoutMs = opts.timeoutMs ?? 15000;
  }

  private async call<T>(method: "GET" | "POST", path: string, body?: unknown): Promise<T> {
    const headers: Record<string, string> = { "Content-Type": "application/json" };
    if (this.key) headers["Authorization"] = "Bearer " + this.key;
    const res = await fetch(this.base + "/v1" + path, {
      method, headers, body: body === undefined ? undefined : JSON.stringify(body), signal: AbortSignal.timeout(this.timeoutMs),
    });
    const text = await res.text();
    let data: unknown = undefined;
    try { data = text ? JSON.parse(text) : undefined; } catch { /* non-JSON */ }
    if (!res.ok) {
      const msg = (data as { error?: string } | undefined)?.error ?? res.statusText;
      throw res.status === 403 ? new Refused(msg) : new NodError(res.status, msg);
    }
    return data as T;
  }

  // anyone
  passport(agentId: string) { return this.call<Passport>("GET", `/passports/${encodeURIComponent(agentId)}`); }
  agentCard(agentId: string) { return this.call<Record<string, unknown>>("GET", `/agents/${encodeURIComponent(agentId)}/agent-card`); }
  verifyMessage(code: string) { return this.call<Record<string, unknown>>("GET", `/verify/${encodeURIComponent(code)}`); }

  // agents (atk_ key)
  ask(a: { counterparty: string; action: string; amount: number; ref: string; reason?: string; currency?: string }) {
    return this.call<NodRequest>("POST", "/nods", { currency: "GBP", reason: "", ...a });
  }
  nodStatus(nodId: string) { return this.call<NodStatus>("GET", `/nods/${encodeURIComponent(nodId)}`); }
  async waitForNod(nodId: string, timeoutMs = 600_000, everyMs = 5_000): Promise<NodStatus> {
    const end = Date.now() + timeoutMs;
    for (;;) {
      const n = await this.nodStatus(nodId);
      if (n.status !== "pending" || Date.now() >= end) return n;
      await new Promise((r) => setTimeout(r, everyMs));
    }
  }
  mandate(nodId: string) { return this.call<Record<string, unknown>>("GET", `/nods/${encodeURIComponent(nodId)}/mandate`); }
  signMessage(m: { to: string; body: string; channel?: "email" | "call" | "message"; subject?: string }) {
    return this.call<Record<string, unknown>>("POST", "/outbound", { channel: "email", subject: "", ...m });
  }

  // company systems (stk_ key)
  /** Call before placing an agent-made booking. Throws Refused unless it exactly matches an unused, nodded nod. */
  authoriseBooking(b: { nodId: string; agent: string; counterparty: string; action: string; amount: number; ref: string; currency?: string }) {
    return this.call<Receipt>("POST", "/actions", {
      nod_id: b.nodId, agent: b.agent, counterparty: b.counterparty, action: b.action, amount: b.amount, currency: b.currency ?? "GBP", ref: b.ref,
    });
  }
  /** type: placed (supplier's system) | delivered | disputed (receiving side). */
  reportOutcome(actionId: string, type: "placed" | "delivered" | "disputed" | "claimed_delivered", note = "") {
    return this.call<{ outcome_id: string; counts: boolean }>("POST", "/outcomes", { action_id: actionId, type, note });
  }
  inbox() { return this.call<Record<string, unknown>[]>("GET", "/inbox"); }

  /** Check a Nod webhook. `body` must be the raw request body. Returns the event or throws. */
  static async verifyWebhook(secret: string, body: string | Uint8Array, signatureHeader: string, toleranceSec = 300): Promise<WebhookEvent> {
    const parts = Object.fromEntries(String(signatureHeader).split(",").map((p) => p.split("=", 2)).filter((p) => p.length === 2));
    const t = parts["t"] ?? "", v1 = parts["v1"] ?? "";
    if (!/^\d+$/.test(t) || Math.abs(Date.now() / 1000 - Number(t)) > toleranceSec) throw new Error("webhook timestamp missing or too old");
    const raw = typeof body === "string" ? body : new TextDecoder().decode(body);
    const enc = new TextEncoder();
    const key = await crypto.subtle.importKey("raw", enc.encode(secret), { name: "HMAC", hash: "SHA-256" }, false, ["sign"]);
    const mac = new Uint8Array(await crypto.subtle.sign("HMAC", key, enc.encode(`${t}.${raw}`)));
    const expected = Array.from(mac, (x) => x.toString(16).padStart(2, "0")).join("");
    let diff = expected.length ^ v1.length;
    for (let i = 0; i < Math.min(expected.length, v1.length); i++) diff |= expected.charCodeAt(i) ^ v1.charCodeAt(i);
    if (diff !== 0) throw new Error("webhook signature doesn't match");
    return JSON.parse(raw) as WebhookEvent;
  }
}
