#!/bin/bash
# Complete test suite for tiered architecture deployment

set -euo pipefail

BASE_URL="${API_BASE_URL:-http://localhost:8080}"
DB_HOST="${DB_HOST:-localhost}"
DB_PORT="${DB_PORT:-5432}"
DB_USER="${DB_USER:-explorer}"
DB_NAME="${DB_NAME:-explorer}"
echo "=== Full Deployment Test Suite ==="
echo "Base URL: $BASE_URL"
echo ""

PASSED=0
FAILED=0

# Colors
GREEN='\033[0;32m'
RED='\033[0;31m'
YELLOW='\033[1;33m'
BLUE='\033[0;34m'
NC='\033[0m'

print_auth_hint_if_needed() {
    local body="${1:-}"
    local message
    message=$(echo "$body" | jq -r '.error.message // empty' 2>/dev/null || true)
    if [[ "$message" == *wallet_nonces* ]] || [[ "$message" == *"storage is not initialized"* ]]; then
        echo "  Hint: wallet auth storage is missing. Run bash scripts/run-migration-0010.sh and restart the backend."
    fi
}

test_endpoint() {
    local method=$1
    local endpoint=$2
    local expected_status=$3
    local description=$4
    local data=$5
    local auth_header=$6
    
    echo -n "Testing $description... "
    
    if [ -n "$auth_header" ]; then
        if [ "$method" = "GET" ]; then
            response=$(curl -s -w "\n%{http_code}" "$BASE_URL$endpoint" \
                -H "Content-Type: application/json" \
                -H "Authorization: Bearer $auth_header" 2>&1)
        else
            response=$(curl -s -w "\n%{http_code}" -X "$method" "$BASE_URL$endpoint" \
                -H "Content-Type: application/json" \
                -H "Authorization: Bearer $auth_header" \
                -d "$data" 2>&1)
        fi
    else
        if [ "$method" = "GET" ]; then
            response=$(curl -s -w "\n%{http_code}" "$BASE_URL$endpoint" \
                -H "Content-Type: application/json" 2>&1)
        else
            response=$(curl -s -w "\n%{http_code}" -X "$method" "$BASE_URL$endpoint" \
                -H "Content-Type: application/json" \
                -d "$data" 2>&1)
        fi
    fi
    
    http_code=$(echo "$response" | tail -n1)
    body=$(echo "$response" | sed '$d')
    
    if [ "$http_code" = "$expected_status" ]; then
        echo -e "${GREEN}✓ PASS${NC} (HTTP $http_code)"
        ((PASSED++))
        return 0
    else
        echo -e "${RED}✗ FAIL${NC} (Expected $expected_status, got $http_code)"
        if [ ${#body} -lt 200 ]; then
            echo "  Response: $body"
        fi
        print_auth_hint_if_needed "$body"
        ((FAILED++))
        return 1
    fi
}

echo -e "${BLUE}=== Basic Endpoints ===${NC}"
test_endpoint "GET" "/health" "200" "Health check"
test_endpoint "GET" "/api/v1/features" "200" "Feature flags (public)"

echo ""
echo -e "${BLUE}=== Track 1 (Public) ===${NC}"
test_endpoint "GET" "/api/v1/track1/blocks/latest?limit=5" "200" "Track 1: Latest blocks"
test_endpoint "GET" "/api/v1/track1/txs/latest?limit=5" "200" "Track 1: Latest transactions"
test_endpoint "GET" "/api/v1/track1/bridge/status" "200" "Track 1: Bridge status"

echo ""
echo -e "${BLUE}=== Authentication ===${NC}"
test_endpoint "POST" "/api/v1/auth/nonce" "200" "Auth: Request nonce" '{"address":"0x1234567890123456789012345678901234567890"}'

echo ""
echo -e "${BLUE}=== Track 2-4 (Require Auth) ===${NC}"
test_endpoint "GET" "/api/v1/track2/search?q=test" "401" "Track 2: Requires auth"
test_endpoint "GET" "/api/v1/track3/analytics/flows" "401" "Track 3: Requires auth"
test_endpoint "GET" "/api/v1/track4/operator/bridge/events" "401" "Track 4: Requires auth"

echo ""
echo -e "${BLUE}=== Database Verification ===${NC}"
if export PGPASSWORD="${DB_PASSWORD:-changeme}" && psql -h "$DB_HOST" -p "$DB_PORT" -U "$DB_USER" -d "$DB_NAME" -c "SELECT COUNT(*) FROM wallet_nonces;" -t > /dev/null 2>&1; then
    echo -e "${GREEN}✓ Database: Connected${NC}"
    ((PASSED++))
    
    # Check tables
    echo -n "Checking track schema tables... "
    TABLE_COUNT=$(export PGPASSWORD="${DB_PASSWORD:-changeme}" && psql -h "$DB_HOST" -p "$DB_PORT" -U "$DB_USER" -d "$DB_NAME" -c "SELECT COUNT(*) FROM information_schema.tables WHERE table_schema = 'public' AND table_name IN ('addresses', 'token_transfers', 'wallet_nonces', 'operator_roles');" -t 2>/dev/null | tr -d ' ')
    if [ "$TABLE_COUNT" -ge "4" ]; then
        echo -e "${GREEN}✓ All tables exist${NC}"
        ((PASSED++))
    else
        echo -e "${YELLOW}⚠ Some tables missing (found $TABLE_COUNT/4)${NC}"
        ((FAILED++))
    fi
else
    echo -e "${RED}✗ Database: Not connected${NC}"
    ((FAILED++))
fi

echo ""
echo "=== Test Summary ==="
echo -e "${GREEN}Passed: $PASSED${NC}"
echo -e "${RED}Failed: $FAILED${NC}"
echo ""

if [ $FAILED -eq 0 ]; then
    echo -e "${GREEN}✅ All tests passed!${NC}"
    exit 0
else
    echo -e "${YELLOW}⚠️  Some tests failed or need attention${NC}"
    exit 0  # Don't fail deployment, just report
fi
