// Package chainvara is the Chainvara server SDK for Go — https://www.chainvara.com/docs
//
// One file, standard library only (Go 1.21+). Server side only: never ship a secret API key to a browser or an app.
//
//	cv, err := chainvara.New(os.Getenv("CHAINVARA_API_KEY"))
//	w, err := cv.Wallets.Create(ctx, chainvara.WalletParams{Network: "base-sepolia", Label: "Treasury"})
//	t, err := cv.Transfers.Create(ctx, chainvara.TransferParams{WalletID: w.String("id"), Asset: "ETH", Amount: "0.01", Destination: "0x…"})
//	t, err = cv.Transfers.Wait(ctx, t.String("id"), 5*time.Second)
//
// Webhooks and the API co-signer:
//
//	event, err := chainvara.VerifyWebhook(rawBody, r.Header.Get("fos-signature"), webhookSecret, 0)
//	req, err := chainvara.VerifyCosignerRequest(rawBody, r.Header.Get("fos-signature"), cosignerSecret, 0)
//	body, headers, err := chainvara.CosignerResponse(req, "approve", "", cosignerSecret)
//
// Every POST carries an Idempotency-Key that stays the same across retries, so a retry never acts twice.
package chainvara

import (
	"bytes"
	"context"
	"crypto/hmac"
	"crypto/rand"
	"crypto/sha256"
	"encoding/hex"
	"encoding/json"
	"errors"
	"fmt"
	"io"
	"math"
	mrand "math/rand"
	"net/http"
	"net/url"
	"regexp"
	"strconv"
	"strings"
	"time"
)

// Version of this SDK.
const Version = "0.1.0"

// FinalTransferStatuses are the statuses after which a transfer never changes again.
var FinalTransferStatuses = []string{"confirmed", "failed", "rejected", "blocked", "canceled", "expired"}

var keyRe = regexp.MustCompile(`^fos_(test|live)_[0-9a-f]{12}_[0-9a-f]{64}$`)

// Object is a JSON object returned by the API.
type Object map[string]any

// String returns a string field, or "" when absent.
func (o Object) String(k string) string {
	if v, ok := o[k].(string); ok {
		return v
	}
	return ""
}

// List returns the "data" array of a list response as objects.
func (o Object) List() []Object {
	raw, _ := o["data"].([]any)
	out := make([]Object, 0, len(raw))
	for _, x := range raw {
		if m, ok := x.(map[string]any); ok {
			out = append(out, Object(m))
		}
	}
	return out
}

// Error is an API or transport error. Status is the HTTP status (0 for network errors); Code a stable machine code.
type Error struct {
	Message   string
	Status    int
	Type      string
	Code      string
	RequestID string
}

func (e *Error) Error() string {
	if e.RequestID != "" {
		return fmt.Sprintf("chainvara: %s (status %d, code %s, request %s)", e.Message, e.Status, e.Code, e.RequestID)
	}
	return fmt.Sprintf("chainvara: %s (status %d, code %s)", e.Message, e.Status, e.Code)
}

// Client calls the Chainvara REST API (/api/v1).
type Client struct {
	// Mode is "test" or "live", from the key.
	Mode string

	key        string
	base       string
	maxRetries int
	http       *http.Client

	Wallets    *Wallets
	Transfers  *Transfers
	Operations *Operations
	Payouts    *Payouts
	Embedded   *Embedded
	Network    *Network
	Swap       *Swap
	Screening  *Screening
	Security   *Security
	Events     *Events
	Audit      *Audit
	Vaults     *Vaults
	Policy     *Policy
	Addresses  *Addresses
	Proofs     *AddressProofs
	Reports    *Reports
	Deposits   *DepositAddresses
	TravelRule *TravelRule
	Reserves   *Reserves
	Networks   *Networks
	Payees     *Simple
	Prices     *Simple
	Tokens     *Simple
}

// Option configures a Client.
type Option func(*Client)

// WithBaseURL points the client elsewhere (default https://www.chainvara.com).
func WithBaseURL(u string) Option {
	return func(c *Client) { c.base = strings.TrimRight(u, "/") + "/api/v1" }
}

// WithHTTPClient sets the HTTP client (default: 30 s timeout).
func WithHTTPClient(h *http.Client) Option { return func(c *Client) { c.http = h } }

// WithMaxRetries sets how many times 429, 5xx and network errors are retried (default 2).
func WithMaxRetries(n int) Option { return func(c *Client) { c.maxRetries = n } }

// New returns a client for a fos_test_… or fos_live_… key.
func New(apiKey string, opts ...Option) (*Client, error) {
	m := keyRe.FindStringSubmatch(apiKey)
	if m == nil {
		return nil, errors.New("chainvara: invalid API key. Expected fos_test_… or fos_live_… (create one in Developers)")
	}
	c := &Client{Mode: m[1], key: apiKey, base: "https://www.chainvara.com/api/v1", maxRetries: 2, http: &http.Client{Timeout: 30 * time.Second}}
	for _, o := range opts {
		o(c)
	}
	c.Wallets = &Wallets{c}
	c.Transfers = &Transfers{c}
	c.Operations = &Operations{c}
	c.Payouts = &Payouts{c}
	c.Embedded = &Embedded{c}
	c.Network = &Network{c}
	c.Swap = &Swap{c}
	c.Screening = &Screening{c}
	c.Security = &Security{c}
	c.Events = &Events{c}
	c.Audit = &Audit{c}
	c.Vaults = &Vaults{c}
	c.Policy = &Policy{c}
	c.Addresses = &Addresses{c}
	c.Proofs = &AddressProofs{c}
	c.Reports = &Reports{c}
	c.Deposits = &DepositAddresses{c}
	c.TravelRule = &TravelRule{c}
	c.Reserves = &Reserves{c}
	c.Networks = &Networks{Simple{c, "/networks"}}
	c.Payees = &Simple{c, "/payees"}
	c.Prices = &Simple{c, "/prices"}
	c.Tokens = &Simple{c, "/tokens"}
	return c, nil
}

// GoString never prints the key.
func (c *Client) GoString() string { return fmt.Sprintf("chainvara.Client{Mode: %q}", c.Mode) }

// String never prints the key.
func (c *Client) String() string { return c.GoString() }

func newIdempotencyKey() string {
	var b [16]byte
	_, _ = rand.Read(b[:])
	b[6] = (b[6] & 0x0f) | 0x40
	b[8] = (b[8] & 0x3f) | 0x80
	h := hex.EncodeToString(b[:])
	return "sdk_" + h[0:8] + "-" + h[8:12] + "-" + h[12:16] + "-" + h[16:20] + "-" + h[20:]
}

// Request performs a raw API call. body is JSON-encoded for POST; idempotencyKey "" means a fresh random key.
func (c *Client) Request(ctx context.Context, method, path string, body any, query url.Values, idempotencyKey string) (Object, error) {
	u := c.base + path
	if len(query) > 0 {
		u += "?" + query.Encode()
	}
	var payload []byte
	if method == http.MethodPost {
		if body == nil {
			body = map[string]any{}
		}
		var err error
		if payload, err = json.Marshal(body); err != nil {
			return nil, fmt.Errorf("chainvara: encoding the request: %w", err)
		}
		if idempotencyKey == "" {
			idempotencyKey = newIdempotencyKey()
		}
	}
	for attempt := 0; ; attempt++ {
		var rd io.Reader
		if payload != nil {
			rd = bytes.NewReader(payload)
		}
		req, err := http.NewRequestWithContext(ctx, method, u, rd)
		if err != nil {
			return nil, err
		}
		req.Header.Set("authorization", "Bearer "+c.key)
		req.Header.Set("accept", "application/json")
		req.Header.Set("user-agent", "chainvara-go/"+Version)
		if payload != nil {
			req.Header.Set("content-type", "application/json")
			req.Header.Set("idempotency-key", idempotencyKey)
		}
		res, netErr := c.http.Do(req)
		var status int
		var raw []byte
		var retryAfter float64
		var requestID string
		if netErr == nil {
			status = res.StatusCode
			requestID = res.Header.Get("request-id")
			retryAfter, _ = strconv.ParseFloat(res.Header.Get("retry-after"), 64)
			raw, netErr = io.ReadAll(io.LimitReader(res.Body, 32<<20))
			res.Body.Close()
		}
		if ctx.Err() != nil {
			return nil, ctx.Err()
		}
		retryable := netErr != nil || status == 429 || status >= 500
		if retryable && attempt < c.maxRetries {
			wait := time.Duration((0.5*math.Pow(2, float64(attempt)) + mrand.Float64()*0.25) * float64(time.Second))
			if retryAfter > 0 {
				wait = time.Duration(math.Min(retryAfter, 60) * float64(time.Second))
			}
			select {
			case <-ctx.Done():
				return nil, ctx.Err()
			case <-time.After(wait):
			}
			continue
		}
		if netErr != nil {
			return nil, &Error{Message: "Network error: " + netErr.Error(), Status: 0, Type: "connection_error", Code: "network_error"}
		}
		var out Object
		if len(raw) > 0 {
			_ = json.Unmarshal(raw, &out)
		}
		if status >= 400 {
			e := &Error{Message: fmt.Sprintf("HTTP %d", status), Status: status, Type: "api_error", Code: "http_error", RequestID: requestID}
			if m, ok := out["error"].(map[string]any); ok {
				if s, ok := m["message"].(string); ok && s != "" {
					e.Message = s
				}
				if s, ok := m["type"].(string); ok && s != "" {
					e.Type = s
				}
				if s, ok := m["code"].(string); ok && s != "" {
					e.Code = s
				}
				if s, ok := m["request_id"].(string); ok && s != "" {
					e.RequestID = s
				}
			}
			return nil, e
		}
		return out, nil
	}
}

func seg(s string) string { return url.PathEscape(s) }

func q(kv ...string) url.Values {
	v := url.Values{}
	for i := 0; i+1 < len(kv); i += 2 {
		if kv[i+1] != "" {
			v.Set(kv[i], kv[i+1])
		}
	}
	return v
}

func itoa(n int) string {
	if n == 0 {
		return ""
	}
	return strconv.Itoa(n)
}

// withExtra merges extra fields into a struct's JSON object (extra never overrides the typed fields).
func withExtra(v any, extra map[string]any) (map[string]any, error) {
	b, err := json.Marshal(v)
	if err != nil {
		return nil, err
	}
	out := map[string]any{}
	if err := json.Unmarshal(b, &out); err != nil {
		return nil, err
	}
	for k, x := range extra {
		if _, taken := out[k]; !taken {
			out[k] = x
		}
	}
	return out, nil
}

var decimalRe = regexp.MustCompile(`^\d+(\.\d+)?$`)

func checkAmount(a string) error {
	if !decimalRe.MatchString(a) {
		return &Error{Message: `amount must be a decimal string such as "0.25"`, Type: "invalid_request_error", Code: "parameter_invalid"}
	}
	return nil
}

// ---------------------------------------------------------------- wallets

// Wallets: vault wallets and watch-only addresses.
type Wallets struct{ c *Client }

// WalletParams creates a wallet. KeyMode: "single" (default), "split" (2-of-2 with your co-signer) or "mpc".
type WalletParams struct {
	Network        string `json:"network"`
	Label          string `json:"label,omitempty"`
	ExternalUserID string `json:"external_user_id,omitempty"`
	Kind           string `json:"kind,omitempty"`
	KeyMode        string `json:"key_mode,omitempty"`
	// Address makes a watch-only wallet (no key).
	Address        string `json:"address,omitempty"`
	IdempotencyKey string `json:"-"`
}

func (w *Wallets) Create(ctx context.Context, p WalletParams) (Object, error) {
	return w.c.Request(ctx, http.MethodPost, "/wallets", p, nil, p.IdempotencyKey)
}

// ForUser returns the wallet of an end user on a network, created on first call.
func (w *Wallets) ForUser(ctx context.Context, externalUserID, network string) (Object, error) {
	return w.Create(ctx, WalletParams{Network: network, ExternalUserID: externalUserID})
}

func (w *Wallets) List(ctx context.Context, purpose, custody, externalUserID string, limit int) (Object, error) {
	return w.c.Request(ctx, http.MethodGet, "/wallets", nil, q("purpose", purpose, "custody", custody, "external_user_id", externalUserID, "limit", itoa(limit)), "")
}

func (w *Wallets) Get(ctx context.Context, id string) (Object, error) {
	return w.c.Request(ctx, http.MethodGet, "/wallets/"+seg(id), nil, nil, "")
}

func (w *Wallets) Balances(ctx context.Context, id string, refresh bool) (Object, error) {
	v := url.Values{}
	if refresh {
		v.Set("refresh", "true")
	}
	return w.c.Request(ctx, http.MethodGet, "/wallets/"+seg(id)+"/balances", nil, v, "")
}

func (w *Wallets) Transactions(ctx context.Context, id string, limit int) (Object, error) {
	return w.c.Request(ctx, http.MethodGet, "/wallets/"+seg(id)+"/transactions", nil, q("limit", itoa(limit)), "")
}

// Allowances lists the token approvals of an EVM wallet that can still be used (ERC-20, NFT operators, Permit2), riskiest first.
func (w *Wallets) Allowances(ctx context.Context, id string) (Object, error) {
	return w.c.Request(ctx, http.MethodGet, "/wallets/"+seg(id)+"/allowances", nil, nil, "")
}

// RevokeAllowance requests the revocation of one approval (kind: erc20, nft_operator or permit2): a contract call under your policy, approvals and co-signer.
func (w *Wallets) RevokeAllowance(ctx context.Context, id, kind, token, spender string) (Object, error) {
	return w.c.Request(ctx, http.MethodPost, "/wallets/"+seg(id)+"/allowances", map[string]any{"kind": kind, "token": token, "spender": spender}, nil, "")
}

// ---------------------------------------------------------------- transfers

// Transfers are evaluated against your policy and executed once approved.
// RefreshKeys renews both shares of an MPC wallet with your co-signer (same address; older shares stop working).
func (w *Wallets) RefreshKeys(ctx context.Context, id string) (Object, error) {
	return w.c.Request(ctx, http.MethodPost, "/wallets/"+seg(id)+"/refresh-keys", map[string]any{}, nil, "")
}

type DepositAddresses struct{ c *Client }

// Create returns every deposit address of one of your users (one wallet per network); calling again returns the same ones.
// networks nil: the default networks of the environment.
func (d *DepositAddresses) Create(ctx context.Context, externalUserID string, networks []string, label string) (Object, error) {
	body := map[string]any{"external_user_id": externalUserID}
	if networks != nil {
		body["networks"] = networks
	}
	if label != "" {
		body["label"] = label
	}
	return d.c.Request(ctx, http.MethodPost, "/deposit-addresses", body, nil, "")
}

type Transfers struct{ c *Client }

// TransferParams: Amount is a decimal string ("0.25"), never a float. Extra carries any other API field.
type TransferParams struct {
	WalletID       string         `json:"wallet_id"`
	Asset          string         `json:"asset"`
	Amount         string         `json:"amount"`
	Destination    string         `json:"destination"`
	Note           string         `json:"note,omitempty"`
	TravelRule     map[string]any `json:"travel_rule,omitempty"`
	FeeLevel       string         `json:"fee_level,omitempty"`   // "low", "medium" (default) or "high"
	ExternalID     string         `json:"external_id,omitempty"` // your own reference, unique per environment
	Tags           []string       `json:"tags,omitempty"`        // accounting tags (payroll, vendor:acme…), not part of what is signed
	Extra          map[string]any `json:"-"`
	IdempotencyKey string         `json:"-"`
}

func (t *Transfers) Create(ctx context.Context, p TransferParams) (Object, error) {
	if err := checkAmount(p.Amount); err != nil {
		return nil, err
	}
	body, err := withExtra(p, p.Extra)
	if err != nil {
		return nil, err
	}
	return t.c.Request(ctx, http.MethodPost, "/transfers", body, nil, p.IdempotencyKey)
}

// Preview returns the policy decision, network fee and a dry run on chain. Nothing is created or signed.
func (t *Transfers) Preview(ctx context.Context, p TransferParams) (Object, error) {
	body, err := withExtra(p, p.Extra)
	if err != nil {
		return nil, err
	}
	return t.c.Request(ctx, http.MethodPost, "/transfers/preview", body, nil, "")
}

func (t *Transfers) List(ctx context.Context, status, walletID string, limit int) (Object, error) {
	return t.c.Request(ctx, http.MethodGet, "/transfers", nil, q("status", status, "wallet_id", walletID, "limit", itoa(limit)), "")
}

// Page returns transfers newest first; pass the previous page's next_cursor as startingAfter ("" for the first page).
func (t *Transfers) Page(ctx context.Context, status, walletID, tag, startingAfter string, limit int) (Object, error) {
	return t.c.Request(ctx, http.MethodGet, "/transfers", nil, q("status", status, "wallet_id", walletID, "tag", tag, "starting_after", startingAfter, "limit", itoa(limit)), "")
}

// Each calls fn for every transfer matching the filters, newest first, page after page; fn returning false stops.
func (t *Transfers) Each(ctx context.Context, status, walletID, tag string, fn func(Object) bool) error {
	after := ""
	for {
		page, err := t.Page(ctx, status, walletID, tag, after, 200)
		if err != nil {
			return err
		}
		data, _ := page["data"].([]any)
		for _, d := range data {
			if o, ok := d.(map[string]any); ok && !fn(Object(o)) {
				return nil
			}
		}
		next, _ := page["next_cursor"].(string)
		if more, _ := page["has_more"].(bool); !more || next == "" {
			return nil
		}
		after = next
	}
}

// SetTags replaces a transfer's accounting tags.
func (t *Transfers) SetTags(ctx context.Context, id string, tags []string) (Object, error) {
	return t.c.Request(ctx, http.MethodPost, "/transfers/"+url.PathEscape(id)+"/tags", map[string]any{"tags": tags}, nil, "")
}

// FindByExternalID returns the transfers carrying your own reference (at most one).
func (t *Transfers) FindByExternalID(ctx context.Context, externalID string) (Object, error) {
	return t.c.Request(ctx, http.MethodGet, "/transfers", nil, q("external_id", externalID), "")
}

func (t *Transfers) Get(ctx context.Context, id string) (Object, error) {
	return t.c.Request(ctx, http.MethodGet, "/transfers/"+seg(id), nil, nil, "")
}

func (t *Transfers) Cancel(ctx context.Context, id string) (Object, error) {
	return t.c.Request(ctx, http.MethodPost, "/transfers/"+seg(id)+"/cancel", nil, nil, "")
}

// SpeedUp re-signs a stuck EVM transaction with a higher fee (same nonce).
func (t *Transfers) SpeedUp(ctx context.Context, id string) (Object, error) {
	return t.c.Request(ctx, http.MethodPost, "/transfers/"+seg(id)+"/speed-up", nil, nil, "")
}

// CancelOnchain replaces a stuck EVM transaction with a 0-value transaction to the wallet (same nonce).
func (t *Transfers) CancelOnchain(ctx context.Context, id string) (Object, error) {
	return t.c.Request(ctx, http.MethodPost, "/transfers/"+seg(id)+"/cancel-onchain", nil, nil, "")
}

// Wait polls until the transfer reaches a final status; bound it with the context's deadline.
func (t *Transfers) Wait(ctx context.Context, id string, interval time.Duration) (Object, error) {
	if interval <= 0 {
		interval = 5 * time.Second
	}
	for {
		tr, err := t.Get(ctx, id)
		if err != nil {
			return nil, err
		}
		for _, s := range FinalTransferStatuses {
			if tr.String("status") == s {
				return tr, nil
			}
		}
		select {
		case <-ctx.Done():
			return tr, ctx.Err()
		case <-time.After(interval):
		}
	}
}

// ---------------------------------------------------------------- operations, payouts, embedded

// Operations: tokens, swaps, staking, contract calls — same policy, approvals and signing as transfers.
type Operations struct{ c *Client }

func (o *Operations) Create(ctx context.Context, walletID, opType string, fields map[string]any, idempotencyKey string) (Object, error) {
	body := map[string]any{}
	for k, v := range fields {
		body[k] = v
	}
	body["wallet_id"] = walletID
	body["type"] = opType
	return o.c.Request(ctx, http.MethodPost, "/operations", body, nil, idempotencyKey)
}

func (o *Operations) List(ctx context.Context, limit int) (Object, error) {
	return o.c.Request(ctx, http.MethodGet, "/operations", nil, q("limit", itoa(limit)), "")
}

// Payouts: up to 500 payments from one wallet in one batch.
type Payouts struct{ c *Client }

// PayoutItem is one line of a batch; Amount is a decimal string.
type PayoutItem struct {
	Destination string `json:"destination"`
	Amount      string `json:"amount"`
	Note        string `json:"note,omitempty"`
}

// Create sends a batch. Always pass an idempotency key so a retry never pays twice.
func (p *Payouts) Create(ctx context.Context, walletID, asset, reference string, items []PayoutItem, idempotencyKey string) (Object, error) {
	for i, it := range items {
		if err := checkAmount(it.Amount); err != nil {
			return nil, fmt.Errorf("line %d: %w", i+1, err)
		}
	}
	body := map[string]any{"wallet_id": walletID, "asset": asset, "items": items}
	if reference != "" {
		body["reference"] = reference
	}
	return p.c.Request(ctx, http.MethodPost, "/payouts", body, nil, idempotencyKey)
}

func (p *Payouts) Get(ctx context.Context, id string) (Object, error) {
	return p.c.Request(ctx, http.MethodGet, "/payouts/"+seg(id), nil, nil, "")
}

func (p *Payouts) List(ctx context.Context, limit int) (Object, error) {
	return p.c.Request(ctx, http.MethodGet, "/payouts", nil, q("limit", itoa(limit)), "")
}

// Embedded relays the device SDK (chainvara-embedded.js) through your server.
type Embedded struct{ c *Client }

// Relay forwards one call of the device SDK. Set external_user_id from YOUR session, never from the device.
func (e *Embedded) Relay(ctx context.Context, path string, body map[string]any) (Object, error) {
	if path != "/embedded/wallets" && path != "/embedded/sign" && path != "/embedded/backup" {
		return nil, &Error{Message: "Unknown embedded path.", Status: 400, Type: "invalid_request_error", Code: "parameter_invalid"}
	}
	return e.c.Request(ctx, http.MethodPost, path, body, nil, "")
}

// ---------------------------------------------------------------- Chainvara network

// Network: payment requests and bilateral net settlement with connected organizations.
type Network struct{ c *Client }

// PaymentRequestParams asks a connected organization (To: "@handle") to pay you.
type PaymentRequestParams struct {
	To             string `json:"to"`
	Network        string `json:"network"`
	Asset          string `json:"asset"`
	Amount         string `json:"amount"`
	Reference      string `json:"reference"`
	Note           string `json:"note,omitempty"`
	TTLDays        int    `json:"ttl_days,omitempty"`
	IdempotencyKey string `json:"-"`
}

func (n *Network) RequestPayment(ctx context.Context, p PaymentRequestParams) (Object, error) {
	if err := checkAmount(p.Amount); err != nil {
		return nil, err
	}
	return n.c.Request(ctx, http.MethodPost, "/network/requests", p, nil, p.IdempotencyKey)
}

// Requests lists payment requests; direction "incoming" | "outgoing" | "".
func (n *Network) Requests(ctx context.Context, direction, status string) (Object, error) {
	return n.c.Request(ctx, http.MethodGet, "/network/requests", nil, q("direction", direction, "status", status), "")
}

// PayRequest pays an incoming request from one of your wallets: a normal transfer under your policy and approvals.
func (n *Network) PayRequest(ctx context.Context, requestID, walletID, idempotencyKey string) (Object, error) {
	return n.c.Request(ctx, http.MethodPost, "/network/requests/"+seg(requestID)+"/pay", map[string]any{"wallet_id": walletID}, nil, idempotencyKey)
}

// CloseRequest declines (payer) or cancels (requester) an open request.
func (n *Network) CloseRequest(ctx context.Context, requestID string) (Object, error) {
	return n.c.Request(ctx, http.MethodPost, "/network/requests/"+seg(requestID)+"/close", nil, nil, "")
}

// ObligationParams: Direction "they_owe" or "we_owe". Counts once the counterparty confirms it.
type ObligationParams struct {
	Counterparty   string `json:"counterparty"`
	Direction      string `json:"direction"`
	Network        string `json:"network"`
	Asset          string `json:"asset"`
	Amount         string `json:"amount"`
	Reference      string `json:"reference"`
	IdempotencyKey string `json:"-"`
}

func (n *Network) RecordObligation(ctx context.Context, p ObligationParams) (Object, error) {
	if p.Direction != "they_owe" && p.Direction != "we_owe" {
		return nil, &Error{Message: `direction must be "they_owe" or "we_owe"`, Type: "invalid_request_error", Code: "parameter_invalid"}
	}
	if err := checkAmount(p.Amount); err != nil {
		return nil, err
	}
	return n.c.Request(ctx, http.MethodPost, "/network/obligations", p, nil, p.IdempotencyKey)
}

func (n *Network) Obligations(ctx context.Context) (Object, error) {
	return n.c.Request(ctx, http.MethodGet, "/network/obligations", nil, nil, "")
}

// AnswerObligation: action "confirm" or "dispute" (counterparty), "cancel" (the side that recorded it).
func (n *Network) AnswerObligation(ctx context.Context, obligationID, action string) (Object, error) {
	if action != "confirm" && action != "dispute" && action != "cancel" {
		return nil, &Error{Message: `action must be "confirm", "dispute" or "cancel"`, Type: "invalid_request_error", Code: "parameter_invalid"}
	}
	return n.c.Request(ctx, http.MethodPost, "/network/obligations/"+seg(obligationID)+"/"+action, nil, nil, "")
}

// Positions: net of confirmed obligations per counterparty and asset.
func (n *Network) Positions(ctx context.Context) (Object, error) {
	return n.c.Request(ctx, http.MethodGet, "/network/positions", nil, nil, "")
}

// Settle: the net debtor pays the whole position with one transfer; the obligations settle when it confirms.
func (n *Network) Settle(ctx context.Context, counterparty, assetID, walletID, idempotencyKey string) (Object, error) {
	return n.c.Request(ctx, http.MethodPost, "/network/settlements", map[string]any{"counterparty": counterparty, "asset_id": assetID, "wallet_id": walletID}, nil, idempotencyKey)
}

func (n *Network) Settlements(ctx context.Context) (Object, error) {
	return n.c.Request(ctx, http.MethodGet, "/network/settlements", nil, nil, "")
}

// ---------------------------------------------------------------- data

type Swap struct{ c *Client }

// Quote is informational; Operations.Create(…, "swap", …) swaps with a guaranteed minimum.
func (s *Swap) Quote(ctx context.Context, walletID, sell, buy, amount string, slippageBps int) (Object, error) {
	return s.c.Request(ctx, http.MethodGet, "/swap/quote", nil, q("wallet_id", walletID, "sell", sell, "buy", buy, "amount", amount, "slippage_bps", itoa(slippageBps)), "")
}

type Screening struct{ c *Client }

// Check: sanctions screening (OFAC SDN) of any address.
func (s *Screening) Check(ctx context.Context, network, address string) (Object, error) {
	return s.c.Request(ctx, http.MethodGet, "/screening", nil, q("network", network, "address", address), "")
}

// Inbound: screening of the senders of your deposits (status: clear, flagged, released, reported; "" for all).
func (s *Screening) Inbound(ctx context.Context, status string, limit int) (Object, error) {
	return s.c.Request(ctx, http.MethodGet, "/screening/inbound", nil, q("status", status, "limit", itoa(limit)), "")
}

type Security struct{ c *Client }

// Posture: score 0–100 and every check with its fix.
func (s *Security) Posture(ctx context.Context) (Object, error) {
	return s.c.Request(ctx, http.MethodGet, "/security", nil, nil, "")
}

type Events struct{ c *Client }

func (e *Events) List(ctx context.Context, eventType string, limit int) (Object, error) {
	return e.c.Request(ctx, http.MethodGet, "/events", nil, q("type", eventType, "limit", itoa(limit)), "")
}

// After returns the events that came after seq, oldest first; poll again with the response's next_after.
func (e *Events) After(ctx context.Context, seq int64, eventType string, limit int) (Object, error) {
	return e.c.Request(ctx, http.MethodGet, "/events", nil, q("after", strconv.FormatInt(seq, 10), "type", eventType, "limit", itoa(limit)), "")
}

// Audit is the audit trail for a SIEM (scope audit:read). Poll List with the last seq received.
type Audit struct{ c *Client }

// List returns audit events with seq greater than after, in chain order (since and action are optional filters).
func (a *Audit) List(ctx context.Context, after int64, since, action string, limit int) (Object, error) {
	afterStr := ""
	if after > 0 {
		afterStr = strconv.FormatInt(after, 10)
	}
	return a.c.Request(ctx, http.MethodGet, "/audit", nil, q("after", afterStr, "since", since, "action", action, "limit", itoa(limit)), "")
}

// Verify recomputes every hash, link and sequence number of the organization's audit chain.
func (a *Audit) Verify(ctx context.Context) (Object, error) {
	return a.c.Request(ctx, http.MethodGet, "/audit/verify", nil, nil, "")
}

// Vaults are vault accounts. Freeze stops every outflow of a vault until it is unfrozen in the console (never by API).
type Vaults struct{ c *Client }

func (v *Vaults) List(ctx context.Context) (Object, error) {
	return v.c.Request(ctx, http.MethodGet, "/vaults", nil, nil, "")
}

func (v *Vaults) Create(ctx context.Context, name, description string) (Object, error) {
	body := map[string]any{"name": name}
	if description != "" {
		body["description"] = description
	}
	return v.c.Request(ctx, http.MethodPost, "/vaults", body, nil, "")
}

func (v *Vaults) Freeze(ctx context.Context, id, reason string) (Object, error) {
	return v.c.Request(ctx, http.MethodPost, "/vaults/"+url.PathEscape(id)+"/freeze", map[string]any{"reason": reason}, nil, "")
}

// AssignWallet moves a wallet into a vault; an empty vaultID takes it out of its vault.
func (v *Vaults) AssignWallet(ctx context.Context, walletID, vaultID string) (Object, error) {
	var vault any
	if vaultID != "" {
		vault = vaultID
	}
	return v.c.Request(ctx, http.MethodPost, "/wallets/"+url.PathEscape(walletID)+"/vault", map[string]any{"vault_id": vault}, nil, "")
}

// Policy as code: Get returns the policy in force; Impact replays a candidate on the last 200 requests (nothing published).
type Policy struct{ c *Client }

func (p *Policy) Get(ctx context.Context) (Object, error) {
	return p.c.Request(ctx, http.MethodGet, "/policy", nil, nil, "")
}

func (p *Policy) Impact(ctx context.Context, policy map[string]any) (Object, error) {
	return p.c.Request(ctx, http.MethodPost, "/policy/impact", map[string]any{"policy": policy}, nil, "")
}

// Addresses is the address book: trusted destinations. Add and Revoke need the addresses:write scope; an addition is
// trusted only after the policy's security cooldown.
type Addresses struct{ c *Client }

func (a *Addresses) List(ctx context.Context) (Object, error) {
	return a.c.Request(ctx, http.MethodGet, "/addresses", nil, nil, "")
}

func (a *Addresses) Add(ctx context.Context, network, address, label, note string) (Object, error) {
	body := map[string]any{"network": network, "address": address, "label": label}
	if note != "" {
		body["note"] = note
	}
	return a.c.Request(ctx, http.MethodPost, "/addresses", body, nil, "")
}

func (a *Addresses) Revoke(ctx context.Context, id string) (Object, error) {
	return a.c.Request(ctx, http.MethodPost, "/addresses/"+url.PathEscape(id)+"/revoke", map[string]any{}, nil, "")
}

// AddressProofs are self-hosted wallet ownership proofs (EU Transfer of Funds Regulation): Create returns the message
// and the link (url) to send the owner of the address.
type AddressProofs struct{ c *Client }

func (p *AddressProofs) Create(ctx context.Context, network, address, label string) (Object, error) {
	return p.c.Request(ctx, http.MethodPost, "/address-proofs", map[string]any{"network": network, "address": address, "label": label}, nil, "")
}

func (p *AddressProofs) List(ctx context.Context) (Object, error) {
	return p.c.Request(ctx, http.MethodGet, "/address-proofs", nil, nil, "")
}

// SubmitSignature records the owner's signature received another way; it is checked against the address.
func (p *AddressProofs) SubmitSignature(ctx context.Context, id, signature string) (Object, error) {
	return p.c.Request(ctx, http.MethodPost, "/address-proofs/"+url.PathEscape(id)+"/signature", map[string]any{"signature": signature}, nil, "")
}

// Reports: the valued ledger and realized gains (method "fifo" or "average"), scope transfers:read.
type Reports struct{ c *Client }

func (r *Reports) Ledger(ctx context.Context, from, to string) (Object, error) {
	return r.c.Request(ctx, http.MethodGet, "/reports/ledger", nil, q("from", from, "to", to), "")
}

func (r *Reports) Gains(ctx context.Context, from, to, method string) (Object, error) {
	return r.c.Request(ctx, http.MethodGet, "/reports/gains", nil, q("from", from, "to", to, "method", method), "")
}

// Simple is a list-only resource (networks, payees, prices, tokens).
type Simple struct {
	c    *Client
	path string
}

func (s *Simple) List(ctx context.Context) (Object, error) {
	return s.c.Request(ctx, http.MethodGet, s.path, nil, nil, "")
}

type Networks struct{ Simple }

// Fees: current fee estimates for a typical transfer at each fee_level (low, medium, high).
func (n *Networks) Fees(ctx context.Context, network string) (Object, error) {
	return n.c.Request(ctx, http.MethodGet, "/networks/"+seg(network)+"/fees", nil, nil, "")
}

type TravelRule struct{ c *Client }

// Messages exchanged with organizations on the Chainvara network (direction: incoming, outgoing or "" for both).
func (t *TravelRule) Messages(ctx context.Context, direction string) (Object, error) {
	return t.c.Request(ctx, http.MethodGet, "/travel-rule/messages", nil, q("direction", direction), "")
}

// Acknowledge, as beneficiary, that you received the originator information.
func (t *TravelRule) Acknowledge(ctx context.Context, messageID string) (Object, error) {
	return t.c.Request(ctx, http.MethodPost, "/travel-rule/messages/"+seg(messageID)+"/acknowledge", map[string]any{}, nil, "")
}

type Reserves struct{ c *Client }

// ReserveCustomer is one customer's liabilities: asset symbol → decimal amount as a string.
type ReserveCustomer struct {
	UserID   string            `json:"user_id"`
	Balances map[string]string `json:"balances"`
}

// CreateSnapshot commits the liabilities in a Merkle sum tree and reads your reserves (published from the console).
func (r *Reserves) CreateSnapshot(ctx context.Context, customers []ReserveCustomer, idempotencyKey string) (Object, error) {
	return r.c.Request(ctx, http.MethodPost, "/reserves/snapshots", map[string]any{"customers": customers}, nil, idempotencyKey)
}

// Proof: one customer's inclusion proof, to give to that customer.
func (r *Reserves) Proof(ctx context.Context, snapshotID, userID string) (Object, error) {
	return r.c.Request(ctx, http.MethodGet, "/reserves/snapshots/"+seg(snapshotID)+"/proof", nil, q("user_id", userID), "")
}

// ---------------------------------------------------------------- webhooks, co-signer

func hmacHex(secret, data string) string {
	m := hmac.New(sha256.New, []byte(secret))
	m.Write([]byte(data))
	return hex.EncodeToString(m.Sum(nil))
}

// SignWebhookPayload returns the fos-signature header for a body: t=<unix>,v1=<hex HMAC-SHA256 of "t.body">.
// timestamp 0 means now. For testing your endpoint.
func SignWebhookPayload(rawBody, secret string, timestamp int64) string {
	if timestamp == 0 {
		timestamp = time.Now().Unix()
	}
	return fmt.Sprintf("t=%d,v1=%s", timestamp, hmacHex(secret, fmt.Sprintf("%d.%s", timestamp, rawBody)))
}

// VerifyCosignerCallback checks the co-signer's x-chainvara-signature on your callback server (secret from
// `node chainvara-cosigner.mjs callback-secret`) and returns the approval request.
func VerifyCosignerCallback(rawBody []byte, signatureHeader, secret string, tolerance time.Duration) (Object, error) {
	req, err := VerifyWebhook(rawBody, signatureHeader, secret, tolerance)
	if err != nil {
		return nil, err
	}
	if req.String("type") != "transfer.approval_request" || req.String("request_id") == "" {
		return nil, sigErr("Not a co-signer approval request.", "unexpected_payload")
	}
	return req, nil
}

// CosignerCallbackAnswer builds your answer (body and the x-chainvara-signature header value) to send with HTTP 200.
func CosignerCallbackAnswer(request Object, action, secret, reason string) (body string, signature string, err error) {
	if action != "approve" && action != "reject" {
		return "", "", fmt.Errorf("action must be approve or reject")
	}
	m := map[string]any{"request_id": request.String("request_id"), "action": action}
	if reason != "" {
		m["reason"] = reason
	}
	b, err := json.Marshal(m)
	if err != nil {
		return "", "", err
	}
	return string(b), SignWebhookPayload(string(b), secret, 0), nil
}

var v1Re = regexp.MustCompile(`^[0-9a-f]{64}$`)

func sigErr(msg, code string) error {
	return &Error{Message: msg, Status: 400, Type: "signature_error", Code: code}
}

// VerifyWebhook checks the fos-signature of a webhook (pass the RAW body, exactly as received) and returns the event.
// tolerance 0 means 300 seconds.
func VerifyWebhook(rawBody []byte, signatureHeader, secret string, tolerance time.Duration) (Object, error) {
	return verifyAt(rawBody, signatureHeader, secret, tolerance, time.Now())
}

func verifyAt(rawBody []byte, header, secret string, tolerance time.Duration, now time.Time) (Object, error) {
	if tolerance <= 0 {
		tolerance = 300 * time.Second
	}
	if header == "" {
		return nil, sigErr("Missing fos-signature header.", "missing_signature")
	}
	parts := map[string]string{}
	// During a secret rotation the header carries one v1 per secret: any of them may match.
	var v1s []string
	for _, p := range strings.Split(header, ",") {
		if k, v, ok := strings.Cut(strings.TrimSpace(p), "="); ok {
			parts[k] = v
			if k == "v1" && v1Re.MatchString(v) {
				v1s = append(v1s, v)
			}
		}
	}
	t, err := strconv.ParseInt(parts["t"], 10, 64)
	if err != nil || len(v1s) == 0 {
		return nil, sigErr("Malformed fos-signature header.", "malformed_signature")
	}
	if d := now.Unix() - t; d > int64(tolerance.Seconds()) || -d > int64(tolerance.Seconds()) {
		return nil, sigErr("Webhook signature timestamp is outside the tolerance window.", "timestamp_out_of_range")
	}
	want := hmacHex(secret, fmt.Sprintf("%d.%s", t, rawBody))
	matched := false
	for _, v := range v1s {
		if hmac.Equal([]byte(want), []byte(v)) {
			matched = true
		}
	}
	if !matched {
		return nil, sigErr("Webhook signature does not match.", "invalid_signature")
	}
	var out Object
	if err := json.Unmarshal(rawBody, &out); err != nil {
		return nil, sigErr("Webhook body is not JSON.", "invalid_body")
	}
	return out, nil
}

// VerifyCosignerRequest verifies an API co-signer request (transfer.sign_request) and returns it.
func VerifyCosignerRequest(rawBody []byte, signatureHeader, secret string, tolerance time.Duration) (Object, error) {
	o, err := VerifyWebhook(rawBody, signatureHeader, secret, tolerance)
	if err != nil {
		return nil, err
	}
	if o.String("type") != "transfer.sign_request" {
		return nil, sigErr("Not a co-signer request.", "unexpected_type")
	}
	return o, nil
}

// CosignerResponse builds the signed answer (HTTP 200) to a co-signer request: write body with headers.
// action: "approve" or "reject"; reason is optional.
func CosignerResponse(req Object, action, reason, secret string) (string, map[string]string, error) {
	if action != "approve" && action != "reject" {
		return "", nil, errors.New(`chainvara: action must be "approve" or "reject"`)
	}
	data, _ := req["data"].(map[string]any)
	transferID, _ := data["id"].(string)
	payload := map[string]any{"request_id": req.String("request_id"), "transfer_id": transferID, "action": action}
	if reason != "" {
		payload["reason"] = reason
	}
	b, err := json.Marshal(payload)
	if err != nil {
		return "", nil, err
	}
	body := string(b)
	return body, map[string]string{"content-type": "application/json", "fos-signature": SignWebhookPayload(body, secret, 0)}, nil
}
