#!/usr/bin/env bash
# Demo of the card API against a running simulator: purchase a card, activate
# it, look it up, check its balance and transactions, ask for the status of the
# purchase, place a card order and check it, lock the card, and try to lock it
# again.
#
# Only active endpoints are used (14 are active, see the README). The others answer 404.
# Not shown: 4.2, 4.6, 4.8, 4.13 and 4.14; the tests show them.
#
#   mix run --no-halt     # in another terminal
#   bash demo.sh          # set YSP_SIM_PORT if the simulator isn't on 4180
#
# Each step prints the request (without the msgHdr) and the response, and a
# table of all the steps is printed at the end.
#
# Resets the simulator first, so it can be run any number of times.

set -euo pipefail

PORT="${YSP_SIM_PORT:-4180}"
SIM="http://localhost:$PORT"
API="$SIM/naradaapiservices/api/v1"
HEADERS=(-H 'clientid: SNDBOX' -H 'channeltype: API'
         -H 'timestamp: 01234567891212' -H 'content-type: application/json')
NETID=APIUSER
LAST_RESPONSE=$(mktemp)
SUMMARY=$(mktemp)
trap 'rm -f "$LAST_RESPONSE" "$SUMMARY"' EXIT
MSG_HDR='"msgHdr":{"msgId":"DEMO","timestamp":"2026-10-26T10:00:00Z","channelType":"web"}'

# call <title> <path> <apikey> <body fields>: prints the request and the
# pretty-printed response, and adds a row to the summary table. METHOD
# (default POST), NETID and FIELDS (a comma-separated list of the response
# fields to show) can be set per call.
call() {
  local method="${METHOD:-POST}"
  echo
  echo "== $1"
  echo "-> $method /naradaapiservices/api/v1/$2   (apikey: $3, netid: $NETID)"
  echo "{$MSG_HDR,$4}" | python3 -c "
import sys, json
body = json.load(sys.stdin)
body.pop('msgHdr', None)
print(json.dumps(body, indent=2))" | sed 's/^/   /'
  curl -s -X "$method" "$API/$2" -H "apikey: $3" -H "netid: $NETID" "${HEADERS[@]}" \
    -d "{$MSG_HDR,$4}" > "$LAST_RESPONSE"
  echo "<- response"
  python3 -c "
import json, os
r = json.load(open('$LAST_RESPONSE'))
if os.environ.get('FIELDS'):
    r = {k: r[k] for k in os.environ['FIELDS'].split(',') if k in r}
print(json.dumps(r, indent=2))" | sed 's/^/   /'
  python3 -c "
import sys, json
r = json.load(open('$LAST_RESPONSE'))
print('|'.join(['$1', '$method $2', r.get('responseCode', '-'), r.get('responseText', '-')]))" >> "$SUMMARY"
}

# field <name>: reads a top-level field from the JSON on stdin.
field() { python3 -c "import sys, json; print(json.load(sys.stdin)['$1'])"; }
last() { field "$1" < "$LAST_RESPONSE"; }

if ! curl -s -o /dev/null "$SIM/_sim/requests"; then
  echo "No simulator on port $PORT. Start it with: mix run --no-halt" >&2
  exit 1
fi

curl -s -o /dev/null -X POST "$SIM/_sim/reset"

call "4.1 Purchase Card" customerregistration APNCRD \
  "\"txnRefNo\":\"DEMO01\",\"customerId\":\"CUST01\",\"nameOnCard\":\"Demo User\",
  \"customerInfo\":{\"mobileNumber\":\"971500000000\",\"emailAddress\":\"demo@example.com\"},
  \"loadDetails\":{\"productCode\":\"MCCAED\",\"billingAmount\":\"500\"}"

proxy=$(last proxyNumber)
code=$(last activationCode)

call "4.5 Card Activation" cardactivation APCDAC \
  "\"txnRefNo\":\"DEMO02\",\"proxyNumber\":\"$proxy\",\"activationCode\":\"$code\""
call "4.3 Get Card Details (cardStatus I = active)" carddetails APCHDT \
  "\"txnRefNo\":\"DEMO03\",\"proxyNumber\":\"$proxy\""
today=$(date +%d%m%Y)
yesterday=$(date -d yesterday +%d%m%Y)

METHOD=GET call "4.9 Query Balance (a GET with a JSON body)" cardbalance APACBL \
  "\"txnRefNo\":\"DEMO09\",\"proxyNumber\":\"$proxy\""
METHOD=GET call "4.12 Get X Transactions" transactiondetails APXTXN \
  "\"txnRefNo\":\"DEMO10\",\"proxyNumber\":\"$proxy\",\"fromDate\":\"$yesterday\",\"toDate\":\"$today\",\"count\":\"5\""
METHOD=GET call "4.20 Status Request for the Purchase Card call (DEMO01)" statusrequest APSTRQ \
  "\"txnRefNo\":\"DEMO01\""

call "4.16 Card Order" cardorder APCROR \
  "\"txnRefNo\":\"DEMO11\",\"order\":{\"productCode\":\"MCCAED\",\"cardDesign\":\"BASEPL\",\"quantity\":\"2\"}"
invoice=$(last invoiceNo)
METHOD=GET call "4.30 Card Order Status" cardorderstatus APCOST \
  "\"txnRefNo\":\"DEMO12\",\"invoiceNo\":\"$invoice\""

call "4.4 Lock the card" cardlockunlock ACDSTS \
  "\"txnRefNo\":\"DEMO04\",\"proxyNumber\":\"$proxy\",\"flag\":\"L\",\"reason\":\"Demo\""
call "4.4 Lock it again (expect MATCRD: already locked)" cardlockunlock ACDSTS \
  "\"txnRefNo\":\"DEMO05\",\"proxyNumber\":\"$proxy\",\"flag\":\"L\",\"reason\":\"Demo\""

echo
echo "== Summary"
{ echo "Step|Call|Code|Text"; cat "$SUMMARY"; } | column -t -s '|'
