#!/bin/bash
# Smoke Tests for Sankofa Phoenix
# Run critical user flows to verify system health

set -e

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

# Configuration
API_URL="${API_URL:-https://api.sankofa.nexus}"
PORTAL_URL="${PORTAL_URL:-https://portal.sankofa.nexus}"
KEYCLOAK_URL="${KEYCLOAK_URL:-https://keycloak.sankofa.nexus}"

# Test results
PASSED=0
FAILED=0
SKIPPED=0

# Helper functions
log_info() {
    echo -e "${GREEN}[INFO]${NC} $1"
}

log_error() {
    echo -e "${RED}[ERROR]${NC} $1"
}

log_warn() {
    echo -e "${YELLOW}[WARN]${NC} $1"
}

test_pass() {
    log_info "✓ $1"
    ((PASSED++))
}

test_fail() {
    log_error "✗ $1"
    ((FAILED++))
}

test_skip() {
    log_warn "⊘ $1 (skipped)"
    ((SKIPPED++))
}

# Test functions
test_api_health() {
    log_info "Testing API health endpoint..."
    if curl -sf "${API_URL}/health" > /dev/null; then
        test_pass "API health check"
    else
        test_fail "API health check"
        return 1
    fi
}

test_api_graphql() {
    log_info "Testing GraphQL endpoint..."
    RESPONSE=$(curl -sf -X POST "${API_URL}/graphql" \
        -H "Content-Type: application/json" \
        -d '{"query": "{ __typename }"}' || echo "ERROR")
    
    if [[ "$RESPONSE" == *"__typename"* ]] || [[ "$RESPONSE" == *"data"* ]]; then
        test_pass "GraphQL endpoint"
    else
        test_fail "GraphQL endpoint"
        return 1
    fi
}

test_portal_health() {
    log_info "Testing Portal health endpoint..."
    if curl -sf "${PORTAL_URL}/api/health" > /dev/null; then
        test_pass "Portal health check"
    else
        test_fail "Portal health check"
        return 1
    fi
}

test_keycloak_health() {
    log_info "Testing Keycloak health endpoint..."
    if curl -sf "${KEYCLOAK_URL}/health" > /dev/null; then
        test_pass "Keycloak health check"
    else
        test_fail "Keycloak health check"
        return 1
    fi
}

test_database_connectivity() {
    log_info "Testing database connectivity..."
    # This requires kubectl access
    if command -v kubectl &> /dev/null; then
        if kubectl exec -n api deployment/api -- \
            psql "${DATABASE_URL}" -c "SELECT 1" > /dev/null 2>&1; then
            test_pass "Database connectivity"
        else
            test_fail "Database connectivity"
            return 1
        fi
    else
        test_skip "Database connectivity (kubectl not available)"
    fi
}

test_authentication() {
    log_info "Testing authentication flow..."
    # Test Keycloak OIDC discovery
    if curl -sf "${KEYCLOAK_URL}/.well-known/openid-configuration" > /dev/null; then
        test_pass "Keycloak OIDC discovery"
    else
        test_fail "Keycloak OIDC discovery"
        return 1
    fi
}

test_rate_limiting() {
    log_info "Testing rate limiting..."
    # Make multiple rapid requests
    local count=0
    for i in {1..10}; do
        if curl -sf "${API_URL}/health" > /dev/null; then
            ((count++))
        fi
    done
    
    if [ $count -gt 0 ]; then
        test_pass "Rate limiting (health endpoint accessible)"
    else
        test_fail "Rate limiting"
        return 1
    fi
}

test_cors_headers() {
    log_info "Testing CORS headers..."
    RESPONSE=$(curl -sf -X OPTIONS "${API_URL}/graphql" \
        -H "Origin: https://portal.sankofa.nexus" \
        -H "Access-Control-Request-Method: POST" \
        -v 2>&1 || echo "ERROR")
    
    if [[ "$RESPONSE" == *"access-control-allow-origin"* ]]; then
        test_pass "CORS headers"
    else
        test_skip "CORS headers (may not be configured)"
    fi
}

test_security_headers() {
    log_info "Testing security headers..."
    RESPONSE=$(curl -sf -I "${API_URL}/health" || echo "ERROR")
    
    local has_csp=false
    local has_hsts=false
    
    if [[ "$RESPONSE" == *"content-security-policy"* ]] || [[ "$RESPONSE" == *"Content-Security-Policy"* ]]; then
        has_csp=true
    fi
    
    if [[ "$RESPONSE" == *"strict-transport-security"* ]] || [[ "$RESPONSE" == *"Strict-Transport-Security"* ]]; then
        has_hsts=true
    fi
    
    if [ "$has_csp" = true ] || [ "$has_hsts" = true ]; then
        test_pass "Security headers"
    else
        test_skip "Security headers (may not be configured)"
    fi
}

# Main execution
main() {
    echo "=========================================="
    echo "Sankofa Phoenix Smoke Tests"
    echo "=========================================="
    echo ""
    echo "API URL: ${API_URL}"
    echo "Portal URL: ${PORTAL_URL}"
    echo "Keycloak URL: ${KEYCLOAK_URL}"
    echo ""
    
    # Run tests
    test_api_health
    test_api_graphql
    test_portal_health
    test_keycloak_health
    test_database_connectivity
    test_authentication
    test_rate_limiting
    test_cors_headers
    test_security_headers
    
    # Summary
    echo ""
    echo "=========================================="
    echo "Test Summary"
    echo "=========================================="
    echo "Passed:  ${GREEN}${PASSED}${NC}"
    echo "Failed:  ${RED}${FAILED}${NC}"
    echo "Skipped: ${YELLOW}${SKIPPED}${NC}"
    echo ""
    
    if [ $FAILED -eq 0 ]; then
        log_info "All critical tests passed!"
        exit 0
    else
        log_error "Some tests failed. Please investigate."
        exit 1
    fi
}

# Run main function
main "$@"

