#!/bin/bash

# SoftPOS OAuth2.0 API Test Script
# This script tests the complete OAuth flow and transaction processing

# Color codes for output
GREEN='\033[0;32m'
BLUE='\033[0;34m'
RED='\033[0;31m'
NC='\033[0m' # No Color

# Configuration
BASE_URL="http://localhost:4066"
CLIENT_ID="softpos_dev_client"
CLIENT_SECRET="dev_secret_123"

echo -e "${BLUE}━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━${NC}"
echo -e "${BLUE}  SoftPOS OAuth2.0 API Test Script${NC}"
echo -e "${BLUE}━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━${NC}"
echo ""

# Step 1: Get Access Token using Client Credentials
echo -e "${BLUE}[1] Getting access token with client credentials...${NC}"
TOKEN_RESPONSE=$(curl -s -X POST "${BASE_URL}/api/soft-pos/oauth/token" \
  -H "Content-Type: application/x-www-form-urlencoded" \
  -d "grant_type=client_credentials" \
  -d "client_id=${CLIENT_ID}" \
  -d "client_secret=${CLIENT_SECRET}" \
  -d "scope=transaction:write")

echo "$TOKEN_RESPONSE" | jq '.'

ACCESS_TOKEN=$(echo "$TOKEN_RESPONSE" | jq -r '.access_token')
REFRESH_TOKEN=$(echo "$TOKEN_RESPONSE" | jq -r '.refresh_token')

if [ "$ACCESS_TOKEN" == "null" ] || [ -z "$ACCESS_TOKEN" ]; then
  echo -e "${RED}❌ Failed to get access token${NC}"
  exit 1
fi

echo -e "${GREEN}✅ Access token obtained${NC}"
echo ""

# Step 2: Process a Purchase Transaction
echo -e "${BLUE}[2] Processing a purchase transaction...${NC}"
TRANSACTION_RESPONSE=$(curl -s -X POST "${BASE_URL}/api/soft-pos/transactions" \
  -H "Authorization: Bearer ${ACCESS_TOKEN}" \
  -H "Content-Type: application/json" \
  -d '{
    "transactionType": "purchase",
    "instanceRequest": {
      "id": "test-txn-001",
      "instanceId": "inst-123",
      "merchantId": "merchant-456",
      "organizationId": "org-789",
      "retrievalReferenceNumber": "RRN123456",
      "emvRequestPayload": "MDEyMzQ1Njc4OQ==",
      "pin": {
        "payload": "encrypted_pin_data",
        "type": "DUKPT",
        "encryptedPek": "pek_data",
        "encryptedPekType": "RSA",
        "ksn": "ksn_value"
      },
      "meta": "{\"device\":\"mobile\"}",
      "gatewayId": "gateway-001"
    }
  }')

echo "$TRANSACTION_RESPONSE" | jq '.'

TRANSACTION_ID=$(echo "$TRANSACTION_RESPONSE" | jq -r '.id')

if [ "$TRANSACTION_ID" == "null" ] || [ -z "$TRANSACTION_ID" ]; then
  echo -e "${RED}❌ Failed to process transaction${NC}"
  exit 1
fi

echo -e "${GREEN}✅ Transaction processed successfully${NC}"
echo -e "Transaction ID: ${TRANSACTION_ID}"
echo ""

# Step 3: Check Transaction Status
echo -e "${BLUE}[3] Checking transaction status...${NC}"
STATUS_RESPONSE=$(curl -s -X GET "${BASE_URL}/api/soft-pos/transactions/${TRANSACTION_ID}" \
  -H "Authorization: Bearer ${ACCESS_TOKEN}")

echo "$STATUS_RESPONSE" | jq '.'
echo -e "${GREEN}✅ Transaction status retrieved${NC}"
echo ""

# Step 4: Test Invalid Token
echo -e "${BLUE}[4] Testing invalid token (should fail)...${NC}"
INVALID_RESPONSE=$(curl -s -X POST "${BASE_URL}/api/soft-pos/transactions" \
  -H "Authorization: Bearer invalid_token_12345" \
  -H "Content-Type: application/json" \
  -d '{"transactionType": "purchase", "instanceRequest": {}}')

echo "$INVALID_RESPONSE" | jq '.'
echo -e "${GREEN}✅ Invalid token correctly rejected${NC}"
echo ""

# Step 5: Refresh Token
echo -e "${BLUE}[5] Refreshing access token...${NC}"
REFRESH_RESPONSE=$(curl -s -X POST "${BASE_URL}/api/soft-pos/oauth/token" \
  -H "Content-Type: application/x-www-form-urlencoded" \
  -d "grant_type=refresh_token" \
  -d "refresh_token=${REFRESH_TOKEN}" \
  -d "client_id=${CLIENT_ID}" \
  -d "client_secret=${CLIENT_SECRET}")

echo "$REFRESH_RESPONSE" | jq '.'

NEW_ACCESS_TOKEN=$(echo "$REFRESH_RESPONSE" | jq -r '.access_token')

if [ "$NEW_ACCESS_TOKEN" == "null" ] || [ -z "$NEW_ACCESS_TOKEN" ]; then
  echo -e "${RED}❌ Failed to refresh token${NC}"
  exit 1
fi

echo -e "${GREEN}✅ Token refreshed successfully${NC}"
echo ""

# Step 6: Use Refreshed Token
echo -e "${BLUE}[6] Using refreshed token for another transaction...${NC}"
SECOND_TRANSACTION=$(curl -s -X POST "${BASE_URL}/api/soft-pos/transactions" \
  -H "Authorization: Bearer ${NEW_ACCESS_TOKEN}" \
  -H "Content-Type: application/json" \
  -d '{
    "transactionType": "refund",
    "instanceRequest": {
      "id": "test-refund-001",
      "merchantId": "merchant-456",
      "organizationId": "org-789",
      "linkedRefundRequestData": {
        "originalTransactionId": "'${TRANSACTION_ID}'",
        "amount": 1000,
        "currency": "USD"
      }
    }
  }')

echo "$SECOND_TRANSACTION" | jq '.'
echo -e "${GREEN}✅ Refreshed token works correctly${NC}"
echo ""

# Summary
echo -e "${BLUE}━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━${NC}"
echo -e "${GREEN}✅ All tests passed successfully!${NC}"
echo -e "${BLUE}━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━${NC}"
echo ""
echo "Test Summary:"
echo "  ✓ Client credentials grant"
echo "  ✓ Transaction processing (purchase)"
echo "  ✓ Transaction status retrieval"
echo "  ✓ Invalid token rejection"
echo "  ✓ Refresh token grant"
echo "  ✓ Refund transaction"
echo ""
