#!/bin/bash
# System Integration Test Script

echo "🔍 System Integration Test"
echo "======================================"
echo ""

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

PASSED=0
FAILED=0

# Test function
test_endpoint() {
    local name="$1"
    local url="$2"
    local expected="$3"
    
    printf "Testing: %-30s " "$name"
    
    response=$(curl -s -o /dev/null -w "%{http_code}" --max-time 3 "$url" 2>/dev/null)
    
    if [ "$response" = "$expected" ]; then
        echo -e "${GREEN}✓ PASS${NC} (HTTP $response)"
        ((PASSED++))
        return 0
    else
        echo -e "${RED}✗ FAIL${NC} (HTTP $response, expected $expected)"
        ((FAILED++))
        return 1
    fi
}

# Test JSON response
test_json_endpoint() {
    local name="$1"
    local url="$2"
    
    printf "Testing: %-30s " "$name"
    
    response=$(curl -s --max-time 3 "$url" 2>/dev/null)
    
    if echo "$response" | jq -e '.success == true' > /dev/null 2>&1; then
        echo -e "${GREEN}✓ PASS${NC} (Valid JSON)"
        ((PASSED++))
        return 0
    else
        echo -e "${RED}✗ FAIL${NC} (Invalid or error response)"
        ((FAILED++))
        return 1
    fi
}

echo "Backend API Tests:"
echo "-------------------"
test_endpoint "Health Check" "http://localhost:8080/health" "200"
test_json_endpoint "Songs API" "http://localhost:8080/api/songs"
test_json_endpoint "Profiles API" "http://localhost:8080/api/profiles"
test_json_endpoint "Lists API" "http://localhost:8080/api/lists"
test_json_endpoint "Stats API" "http://localhost:8080/api/stats"

echo ""
echo "Frontend Tests:"
echo "-------------------"
test_endpoint "Local Frontend" "http://localhost:5100" "200"
test_endpoint "External HTTPS" "https://houseofprayer.ddns.net" "200"

echo ""
echo "Database Tests:"
echo "-------------------"
printf "Testing: %-30s " "PostgreSQL Connection"
if PGPASSWORD='MySecurePass123' psql -U songlyric_user -d church_songlyric -h 192.168.10.130 -c "SELECT 1" > /dev/null 2>&1; then
    echo -e "${GREEN}✓ PASS${NC}"
    ((PASSED++))
else
    echo -e "${RED}✗ FAIL${NC}"
    ((FAILED++))
fi

echo ""
echo "======================================"
echo "Summary:"
echo "  Passed: $PASSED"
echo "  Failed: $FAILED"
echo ""

if [ $FAILED -eq 0 ]; then
    echo -e "${GREEN}✅ All tests passed!${NC}"
    echo "🎉 System is fully operational!"
    exit 0
else
    echo -e "${RED}❌ Some tests failed!${NC}"
    exit 1
fi
