#!/bin/bash
# Submit Test Instruction to AS4 Settlement
# Creates and submits a test settlement instruction

set -e

BASE_URL="${AS4_BASE_URL:-http://localhost:3000}"
AUTH_TOKEN="${AS4_AUTH_TOKEN:-}"
FROM_MEMBER="${1:-TEST-MEMBER-001}"
AMOUNT="${2:-1000.00}"
CURRENCY="${3:-USD}"

INSTR_ID="INSTR-TEST-$(date +%s)"
MSG_ID="MSG-TEST-$(date +%s)"
CORR_ID="CORR-$(date +%s)"
NONCE="nonce-$(date +%s)"

echo "Submitting test instruction: $INSTR_ID"

# Calculate payload hash (simplified)
PAYLOAD_HASH=$(echo -n "$INSTR_ID$FROM_MEMBER$AMOUNT" | sha256sum | cut -d' ' -f1 | tr '[:lower:]' '[:upper:]')

curl -X POST "$BASE_URL/api/v1/as4/settlement/instructions" \
  -H "Content-Type: application/json" \
  ${AUTH_TOKEN:+-H "Authorization: Bearer $AUTH_TOKEN"} \
  -d "{
    \"fromMemberId\": \"$FROM_MEMBER\",
    \"payloadHash\": \"$PAYLOAD_HASH\",
    \"signatureEvidence\": {},
    \"as4ReceiptEvidence\": {},
    \"message\": {
      \"MessageId\": \"$MSG_ID\",
      \"BusinessType\": \"DBIS.SI.202\",
      \"CreatedAt\": \"$(date -u +%Y-%m-%dT%H:%M:%SZ)\",
      \"FromMemberId\": \"$FROM_MEMBER\",
      \"ToMemberId\": \"DBIS\",
      \"CorrelationId\": \"$CORR_ID\",
      \"ReplayNonce\": \"$NONCE\",
      \"SchemaVersion\": \"1.0\",
      \"Instr\": {
        \"InstrId\": \"$INSTR_ID\",
        \"ValueDate\": \"$(date -u +%Y-%m-%d)\",
        \"Currency\": \"$CURRENCY\",
        \"Amount\": \"$AMOUNT\",
        \"DebtorAccount\": \"MSA:$FROM_MEMBER:$CURRENCY\",
        \"CreditorAccount\": \"MSA:TEST-MEMBER-002:$CURRENCY\",
        \"Charges\": \"SHA\",
        \"PurposeCode\": \"SETT\"
      }
    }
  }" | jq '.'

echo ""
echo "Test instruction submitted: $INSTR_ID"
