#!/usr/bin/env bash
set -euo pipefail

# Requires curl and jq. Pass a localhost origin to run against the local application server.
origin=${1:-https://pay.axiv.cc}
api="${origin%/}/mock/v1"
request() {
  curl --fail --silent --show-error --max-time 10 "$@" |
    jq -e 'select(.simulation == true and .mode == "mock")'
}

request "$api/capabilities" >/dev/null
quote=$(request "$api/quotes" -H 'Content-Type: application/json' \
  -d '{"source":{"chainId":"999","asset":"USDC","amountAtomic":"10000000"},"destination":{"chainId":"4663","asset":"USDG","recipient":"0x000000000000000000000000000000000000dEaD"},"fundingMode":"DIRECT"}')
quote_id=$(jq -er '.quoteId' <<< "$quote")
request_key=$(od -An -N16 -tx1 /dev/urandom | tr -d ' \n')
payment=$(request "$api/payments" -H 'Content-Type: application/json' -H "Idempotency-Key: $request_key" \
  -d "$(jq -cn --arg id "$quote_id" '{quoteId: $id, merchantReference: "example-order"}')")
payment_id=$(jq -er '.paymentId' <<< "$payment")

for next in DEPOSIT_OBSERVED GUARANTEED PAYOUT_PENDING PAID SETTLED; do
  current=$(jq -er '.status' <<< "$payment")
  payment=$(request "$api/payments/$payment_id/simulate" -H 'Content-Type: application/json' \
    -d "$(jq -cn --arg state "$current" '{expectedStatus: $state}')")
  jq -e --arg next "$next" '.status == $next' <<< "$payment" >/dev/null
done
events=$(request "$api/payments/$payment_id/events")
jq -e '.events | length == 6 and all(.simulation == true)' <<< "$events" >/dev/null
jq -n --argjson quote "$quote" --argjson payment "$payment" --argjson eventLog "$events" \
  '{quote: $quote, payment: $payment, events: $eventLog.events}'
