#!/usr/bin/env bash

# Test NPCI Callback Endpoints
set -e

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

echo "🚀 Testing NPCI Callback Endpoints"
echo "=================================="

# Function to make HTTP requests with XML
http_post_xml() {
  curl -s -X POST "$1" \
    -H "Content-Type: application/xml" \
    -d "$2"
}

# Test 1: Heartbeat
echo "💓 Test 1: NPCI Heartbeat..."
HEARTBEAT_XML='<?xml version="1.0" encoding="UTF-8"?>
<upi:ReqHbt xmlns:upi="http://npci.org/upi/schema/">
  <Head ver="2.0" ts="2025-08-11T10:30:00Z" orgId="NPCI" msgId="HBT123456"/>
</upi:ReqHbt>'

HEARTBEAT_RESPONSE=$(http_post_xml "$BASE_URL/npci/heartbeat" "$HEARTBEAT_XML")
echo "Response: $HEARTBEAT_RESPONSE"

# Test 2: Check Transaction (will fail - no transaction exists)
echo -e "\n🔍 Test 2: NPCI Check Transaction..."
CHECK_TXN_XML='<?xml version="1.0" encoding="UTF-8"?>
<upi:ReqChkTxn xmlns:upi="http://npci.org/upi/schema/">
  <Head ver="2.0" ts="2025-08-11T10:30:00Z" orgId="NPCI" msgId="CHK123456"/>
  <Txn id="TESTCHK123" note="Check transaction" refId="REF123" refUrl="" 
       refCategory="" ts="2025-08-11T10:30:00Z" custRef="CUST123" type="ChkTxn" 
       orgMsgId="ORIG123" orgTxnId="NONEXISTENT_TXN" orgTxnDate="2025-08-11T10:29:00Z" 
       initiationMode="00" purpose="11" subType="CREDIT"/>
</upi:ReqChkTxn>'

CHECK_RESPONSE=$(http_post_xml "$BASE_URL/npci/check-transaction" "$CHECK_TXN_XML")
echo "Response: $CHECK_RESPONSE"

# Test 3: Reversal Request (will fail - no transaction exists)
echo -e "\n↩️  Test 3: NPCI Reversal Request..."
REVERSAL_XML='<?xml version="1.0" encoding="UTF-8"?>
<upi:ReqPay xmlns:upi="http://npci.org/upi/schema/">
  <Head ver="2.0" ts="2025-08-11T10:30:00Z" orgId="NPCI" msgId="REV123456"/>
  <Txn id="TESTREV123" note="Reversal request" refId="REF123" refUrl="" 
       ts="2025-08-11T10:30:00Z" type="REVERSAL" orgTxnId="NONEXISTENT_TXN" 
       initiationMode="00" purpose="11" custRef="CUST123"/>
</upi:ReqPay>'

REVERSAL_RESPONSE=$(http_post_xml "$BASE_URL/npci/reversal-request" "$REVERSAL_XML")
echo "Response: $REVERSAL_RESPONSE"

echo -e "\n✅ NPCI Callback endpoint tests completed!"
echo "Note: Check/Reversal tests expected to fail since no transactions exist yet."
