#!/usr/bin/env bash
# Fire a fake Xendit Invoice callback at the local backend so you can exercise
# the webhook handler without going through ngrok / a real Xendit invoice.
#
# Usage:
#   ./xendit-fake-webhook.sh <payment_request_id> [PAID|EXPIRED] [amount]
#
# Requires XENDIT_WEBHOOK_TOKEN in your environment. Pull from backend/.env:
#   source <(grep '^XENDIT_WEBHOOK_TOKEN=' ../backend/.env)
#
# NOT a Maestro replacement — Maestro keeps using /internal/_test/force-confirm-payment
# (no token needed, faster). The fake webhook is for testing the handler itself:
# signature verify, idempotency on retry, amount mismatch, etc.

set -euo pipefail

PAYMENT_ID="${1:?usage: $0 <payment_request_id> [PAID|EXPIRED] [amount]}"
STATUS="${2:-PAID}"
AMOUNT="${3:-50000}"
TOKEN="${XENDIT_WEBHOOK_TOKEN:?XENDIT_WEBHOOK_TOKEN env not set}"
BASE_URL="${BASE_URL:-http://localhost:3000}"

INVOICE_ID="inv_fake_$(date +%s)_${RANDOM}"

curl -sS -X POST "${BASE_URL}/api/shared/payment/webhooks/xendit" \
  -H "x-callback-token: ${TOKEN}" \
  -H "content-type: application/json" \
  -d "{
    \"id\": \"${INVOICE_ID}\",
    \"external_id\": \"${PAYMENT_ID}\",
    \"status\": \"${STATUS}\",
    \"amount\": ${AMOUNT},
    \"payment_method\": \"BCA\"
  }" | jq . 2>/dev/null || cat
echo
