#!/usr/bin/env bash
# KAR-761 / Option B — RwG BookingNotification-RTU generator.
# Logs into a merchant dashboard account and cancels (rejects) a source=google
# reservation via the real API → fires an outbound BookingNotification RTU
# (status CANCELED) to Google. Used to generate RTU volume for the
# Onboarding-Health milestones M7 (prod) / M4 (sandbox).
#
# Mechanism (verified 2026-06-22):
#   login : POST https://api.kadicon.de/api/auth/login {email,password} -> access_token
#   read  : GET  /api/reservation/:id            (Bearer + X-TENANT-ID)
#   reject: PATCH /api/reservation/:id/reject     (Bearer + X-TENANT-ID)  <- fires RTU
# tenantId is read from the JWT claims (no hardcoding).
#
# SAFETY: `reject` actually cancels a real booking and notifies Google. It only
# fires when invoked explicitly with the `reject` subcommand AND `--yes`.
#
# Usage:
#   kar761-rwg-rtu.sh login  <merchant>
#   kar761-rwg-rtu.sh get    <merchant> <reservation_id>
#   kar761-rwg-rtu.sh reject <merchant> <reservation_id> --yes
#   merchant ∈ klosterwirt | burgerpoint | gusto
set -euo pipefail

API="https://api.kadicon.de"
CREDS="/root/.aria-secrets/kadicon-merchant-logins.env"
[[ -r "$CREDS" ]] || { echo "FATAL: $CREDS not readable"; exit 1; }
set -a; source "$CREDS"; set +a

merchant_user() { case "$1" in
  klosterwirt) echo "${KLOSTERWIRT_USER:-}";; burgerpoint) echo "${BURGERPOINT_USER:-}";;
  gusto) echo "${GUSTO_USER:-}";; *) echo "";; esac; }
merchant_pass() { case "$1" in
  klosterwirt) echo "${KLOSTERWIRT_PASS:-}";; burgerpoint) echo "${BURGERPOINT_PASS:-}";;
  gusto) echo "${GUSTO_PASS:-}";; *) echo "";; esac; }

login() { # $1=merchant  -> echoes access_token
  local u p; u="$(merchant_user "$1")"; p="$(merchant_pass "$1")"
  [[ -n "$u" && -n "$p" ]] || { echo "FATAL: no creds for merchant '$1'" >&2; exit 1; }
  curl -s --max-time 15 -X POST "$API/api/auth/login" -H "Content-Type: application/json" \
    -d "$(python3 -c 'import json,sys;print(json.dumps({"email":sys.argv[1],"password":sys.argv[2]}))' "$u" "$p")" \
    | python3 -c 'import json,sys;print(json.load(sys.stdin)["access_token"])'
}

tenant_of() { # $1=token
  python3 -c '
import base64,json,sys
p=sys.argv[1].split(".")[1]; p+="="*(-len(p)%4)
print(json.loads(base64.urlsafe_b64decode(p))["tenantId"])' "$1"
}

cmd="${1:-}"; merchant="${2:-}"; rid="${3:-}"
case "$cmd" in
  login)
    tok="$(login "$merchant")"; ten="$(tenant_of "$tok")"
    echo "OK login '$merchant' -> tenantId=$ten (token len ${#tok})";;
  get)
    [[ -n "$rid" ]] || { echo "usage: get <merchant> <reservation_id>"; exit 1; }
    tok="$(login "$merchant")"; ten="$(tenant_of "$tok")"
    curl -s --max-time 15 "$API/api/reservation/$rid" \
      -H "Authorization: Bearer $tok" -H "X-TENANT-ID: $ten" \
      | python3 -c 'import json,sys;d=json.load(sys.stdin);print(json.dumps({k:d.get(k) for k in ("id","state","source","noOfPersons","startDate")},indent=2))';;
  reject)
    [[ -n "$rid" ]] || { echo "usage: reject <merchant> <reservation_id> --yes"; exit 1; }
    [[ "${4:-}" == "--yes" ]] || { echo "REFUSED: reject fires a real cancel + RTU to Google. Re-run with --yes."; exit 2; }
    tok="$(login "$merchant")"; ten="$(tenant_of "$tok")"
    echo "Rejecting $rid (merchant=$merchant tenant=$ten) ..."
    curl -s -w "\nHTTP=%{http_code}\n" --max-time 20 -X PATCH "$API/api/reservation/$rid/reject" \
      -H "Authorization: Bearer $tok" -H "X-TENANT-ID: $ten" -H "Content-Type: application/json";;
  *) echo "usage: $0 {login|get|reject} <merchant> [reservation_id] [--yes]"; exit 1;;
esac
