#!/usr/bin/env bash

# UPI PSP API Test Script
set -e

BASE_URL="http://localhost:4000/api/v1"

echo "🚀 Testing UPI PSP API Endpoints"
echo "================================="

# Function to make HTTP requests
http_post() {
  curl -s -X POST "$1" \
    -H "Content-Type: application/json" \
    -d "$2" | jq .
}

http_get() {
  curl -s "$1" | jq .
}

# Test 1: Create a transaction
echo "📝 Test 1: Creating a transaction..."
TRANSACTION_RESPONSE=$(http_post "$BASE_URL/transactions" '{
  "payer_addr": "user@paytm",
  "payee_addr": "merchant@axis",
  "payee_mid": "MERCHANT001",
  "foreign_amount": "100.00",
  "foreign_currency": "USD",
  "fx_rate": "83.25",
  "markup_pct": "2.5",
  "ver_token": "VER123456"
}')

echo "$TRANSACTION_RESPONSE"

# Extract org_txn_id
ORG_TXN_ID=$(echo "$TRANSACTION_RESPONSE" | jq -r '.data.org_txn_id // empty')

if [ -n "$ORG_TXN_ID" ]; then
  echo "✅ Transaction created with ID: $ORG_TXN_ID"
  
  # Test 2: Get transaction details
  echo -e "\n📋 Test 2: Getting transaction details..."
  http_get "$BASE_URL/transactions/$ORG_TXN_ID"
  
  # Test 3: Simulate credit success
  echo -e "\n💰 Test 3: Simulating credit success..."
  http_post "$BASE_URL/transactions/$ORG_TXN_ID/credit-success" '{}'
  
  # Test 4: Get updated transaction
  echo -e "\n🔄 Test 4: Getting updated transaction..."
  http_get "$BASE_URL/transactions/$ORG_TXN_ID"
else
  echo "❌ Failed to create transaction"
fi

# Test 5: List all transactions
echo -e "\n📊 Test 5: Listing all transactions..."
http_get "$BASE_URL/transactions"

# Test 6: Test QR validation endpoint
echo -e "\n🔍 Test 6: Testing QR validation with sample XML..."
http_post "$BASE_URL/qr-validation" '{
  "xml": "<?xml version=\"1.0\" encoding=\"UTF-8\"?><ReqValQr><Head><msgId>MSG123</msgId><ts>2025-01-01T10:00:00</ts><orgId>NPCIORG</orgId></Head><Qr><addr>merchant@axis</addr><mid>MERCHANT001</mid></Qr></ReqValQr>"
}'

echo -e "\n✅ API testing completed!"
