#!/bin/bash
# AS4 Settlement API Testing Script
# Tests all AS4 API endpoints

set -e

BASE_URL="${AS4_BASE_URL:-http://localhost:3000}"
AUTH_TOKEN="${AS4_AUTH_TOKEN:-}"

echo "========================================="
echo "AS4 Settlement API Testing"
echo "========================================="
echo "Base URL: $BASE_URL"
echo ""

# Colors for output
GREEN='\033[0;32m'
RED='\033[0;31m'
YELLOW='\033[1;33m'
NC='\033[0m' # No Color

PASSED=0
FAILED=0

test_endpoint() {
    local method=$1
    local endpoint=$2
    local data=$3
    local expected_status=$4
    local description=$5

    echo -n "Testing: $description... "
    
    if [ -n "$data" ]; then
        response=$(curl -s -w "\n%{http_code}" -X "$method" \
            "$BASE_URL$endpoint" \
            -H "Content-Type: application/json" \
            ${AUTH_TOKEN:+-H "Authorization: Bearer $AUTH_TOKEN"} \
            -d "$data" 2>&1)
    else
        response=$(curl -s -w "\n%{http_code}" -X "$method" \
            "$BASE_URL$endpoint" \
            ${AUTH_TOKEN:+-H "Authorization: Bearer $AUTH_TOKEN"} 2>&1)
    fi

    http_code=$(echo "$response" | tail -n1)
    body=$(echo "$response" | sed '$d')

    if [ "$http_code" = "$expected_status" ]; then
        echo -e "${GREEN}✓ PASSED${NC} (HTTP $http_code)"
        ((PASSED++))
        return 0
    else
        echo -e "${RED}✗ FAILED${NC} (Expected HTTP $expected_status, got $http_code)"
        echo "  Response: $body"
        ((FAILED++))
        return 1
    fi
}

# Test 1: Health Check
test_endpoint "GET" "/health" "" "200" "Health Check"

# Test 2: AS4 Metrics
test_endpoint "GET" "/api/v1/as4/metrics" "" "200" "Prometheus Metrics"

# Test 3: AS4 Health Metrics
test_endpoint "GET" "/api/v1/as4/metrics/health" "" "200" "Health Metrics"

# Test 4: Member Directory - Search (may fail if no members)
test_endpoint "GET" "/api/v1/as4/directory/members?status=active" "" "200" "Search Members"

# Test 5: Certificate Expiration Warnings
test_endpoint "GET" "/api/v1/as4/directory/certificates/expiration-warnings" "" "200" "Certificate Warnings"

# Summary
echo ""
echo "========================================="
echo "Test Summary"
echo "========================================="
echo -e "${GREEN}Passed: $PASSED${NC}"
if [ $FAILED -gt 0 ]; then
    echo -e "${RED}Failed: $FAILED${NC}"
else
    echo -e "${GREEN}Failed: $FAILED${NC}"
fi
echo ""

if [ $FAILED -eq 0 ]; then
    echo "✓ All API tests passed!"
    exit 0
else
    echo "✗ Some API tests failed"
    exit 1
fi
