#!/bin/bash

# 🧪 Veza Platform - Tests de validation finale
# Version 2.0.0

set -e

# Couleurs pour les messages
RED='\033[0;31m'
GREEN='\033[0;32m'
YELLOW='\033[1;33m'
BLUE='\033[0;34m'
PURPLE='\033[0;35m'
CYAN='\033[0;36m'
NC='\033[0m' # No Color

# Configuration
BACKEND_PORT=8080
FRONTEND_PORT=5173
DESKTOP_PORT=5177

# Compteurs de tests
TOTAL_TESTS=0
PASSED_TESTS=0
FAILED_TESTS=0

# Fonction pour incrémenter les compteurs
increment_test() {
    TOTAL_TESTS=$((TOTAL_TESTS + 1))
}

pass_test() {
    PASSED_TESTS=$((PASSED_TESTS + 1))
    echo -e "${GREEN}✅ PASS${NC}"
}

fail_test() {
    FAILED_TESTS=$((FAILED_TESTS + 1))
    echo -e "${RED}❌ FAIL${NC}"
}

# Fonction pour tester un endpoint
test_endpoint() {
    local name="$1"
    local url="$2"
    local expected_status="$3"
    
    increment_test
    echo -n "Test: $name... "
    
    if curl -s -o /dev/null -w "%{http_code}" "$url" | grep -q "$expected_status"; then
        pass_test
    else
        fail_test
        echo -e "${YELLOW}URL: $url${NC}"
    fi
}

# Fonction pour tester la réponse JSON
test_json_response() {
    local name="$1"
    local url="$2"
    local expected_field="$3"
    
    increment_test
    echo -n "Test: $name... "
    
    response=$(curl -s "$url")
    if echo "$response" | jq -e ".$expected_field" > /dev/null 2>&1; then
        pass_test
    else
        fail_test
        echo -e "${YELLOW}URL: $url${NC}"
        echo -e "${YELLOW}Response: $response${NC}"
    fi
}

# Fonction pour tester la connectivité
test_connectivity() {
    local name="$1"
    local host="$2"
    local port="$3"
    
    increment_test
    echo -n "Test: $name... "
    
    if timeout 5 bash -c "</dev/tcp/$host/$port" 2>/dev/null; then
        pass_test
    else
        fail_test
    fi
}

# Fonction pour tester le contenu HTML
test_html_content() {
    local name="$1"
    local url="$2"
    local expected_content="$3"
    
    increment_test
    echo -n "Test: $name... "
    
    if curl -s "$url" | grep -q "$expected_content"; then
        pass_test
    else
        fail_test
        echo -e "${YELLOW}URL: $url${NC}"
    fi
}

# Fonction pour afficher le résumé
show_summary() {
    echo ""
    echo -e "${PURPLE}📊 Résumé des tests:${NC}"
    echo -e "${CYAN}================================${NC}"
    echo -e "${BLUE}Total des tests:${NC} $TOTAL_TESTS"
    echo -e "${GREEN}Tests réussis:${NC} $PASSED_TESTS"
    echo -e "${RED}Tests échoués:${NC} $FAILED_TESTS"
    
    if [ $FAILED_TESTS -eq 0 ]; then
        echo ""
        echo -e "${GREEN}🎉 Tous les tests sont passés !${NC}"
        echo -e "${GREEN}✅ Veza Platform est prêt pour la production${NC}"
        return 0
    else
        echo ""
        echo -e "${RED}❌ $FAILED_TESTS test(s) ont échoué${NC}"
        echo -e "${YELLOW}⚠️  Veuillez corriger les problèmes avant la production${NC}"
        return 1
    fi
}

# Tests principaux
run_tests() {
    echo -e "${PURPLE}🧪 Veza Platform - Tests de validation finale${NC}"
    echo -e "${CYAN}===============================================${NC}"
    echo ""
    
    echo -e "${BLUE}🔍 Tests de connectivité...${NC}"
    echo -e "${CYAN}------------------------${NC}"
    
    test_connectivity "Backend API" "localhost" $BACKEND_PORT
    test_connectivity "Frontend Web" "localhost" $FRONTEND_PORT
    
    echo ""
    echo -e "${BLUE}🔍 Tests des endpoints API...${NC}"
    echo -e "${CYAN}---------------------------${NC}"
    
    test_endpoint "Health Check" "http://localhost:$BACKEND_PORT/health" "200"
    test_endpoint "API Root" "http://localhost:$BACKEND_PORT/" "200"
    test_endpoint "Tracks API" "http://localhost:$BACKEND_PORT/api/v1/tracks" "200"
    test_endpoint "Analytics API" "http://localhost:$BACKEND_PORT/api/v1/analytics" "200"
    test_endpoint "Users API" "http://localhost:$BACKEND_PORT/api/v1/users" "200"
    test_endpoint "Messages API" "http://localhost:$BACKEND_PORT/api/v1/messages" "200"
    test_endpoint "Marketplace API" "http://localhost:$BACKEND_PORT/api/v1/marketplace" "200"
    test_endpoint "Contests API" "http://localhost:$BACKEND_PORT/api/v1/contests" "200"
    
    echo ""
    echo -e "${BLUE}🔍 Tests des réponses JSON...${NC}"
    echo -e "${CYAN}----------------------------${NC}"
    
    test_json_response "Health JSON" "http://localhost:$BACKEND_PORT/health" "status"
    test_json_response "Tracks JSON" "http://localhost:$BACKEND_PORT/api/v1/tracks" "data"
    test_json_response "Analytics JSON" "http://localhost:$BACKEND_PORT/api/v1/analytics" "data"
    test_json_response "Marketplace JSON" "http://localhost:$BACKEND_PORT/api/v1/marketplace" "data"
    
    echo ""
    echo -e "${BLUE}🔍 Tests du Frontend...${NC}"
    echo -e "${CYAN}----------------------${NC}"
    
    test_endpoint "Frontend Web" "http://localhost:$FRONTEND_PORT" "200"
    test_html_content "Frontend Title" "http://localhost:$FRONTEND_PORT" "Veza Platform"
    test_html_content "Frontend React" "http://localhost:$FRONTEND_PORT" "react"
    
    echo ""
    echo -e "${BLUE}🔍 Tests des fonctionnalités...${NC}"
    echo -e "${CYAN}---------------------------${NC}"
    
    # Test des données mockées
    increment_test
    echo -n "Test: Données mockées disponibles... "
    tracks_response=$(curl -s "http://localhost:$BACKEND_PORT/api/v1/tracks")
    if echo "$tracks_response" | jq -e '.data | length > 0' > /dev/null 2>&1; then
        pass_test
    else
        fail_test
    fi
    
    increment_test
    echo -n "Test: Analytics disponibles... "
    analytics_response=$(curl -s "http://localhost:$BACKEND_PORT/api/v1/analytics")
    if echo "$analytics_response" | jq -e '.data.total_plays' > /dev/null 2>&1; then
        pass_test
    else
        fail_test
    fi
    
    increment_test
    echo -n "Test: Marketplace disponible... "
    marketplace_response=$(curl -s "http://localhost:$BACKEND_PORT/api/v1/marketplace")
    if echo "$marketplace_response" | jq -e '.data | length > 0' > /dev/null 2>&1; then
        pass_test
    else
        fail_test
    fi
    
    echo ""
    echo -e "${BLUE}🔍 Tests de performance...${NC}"
    echo -e "${CYAN}------------------------${NC}"
    
    # Test de latence
    increment_test
    echo -n "Test: Latence Backend API... "
    start_time=$(date +%s%N)
    curl -s "http://localhost:$BACKEND_PORT/health" > /dev/null
    end_time=$(date +%s%N)
    latency=$(( (end_time - start_time) / 1000000 ))
    if [ $latency -lt 1000 ]; then
        pass_test
        echo -e "${GREEN}(${latency}ms)${NC}"
    else
        fail_test
        echo -e "${RED}(${latency}ms)${NC}"
    fi
    
    increment_test
    echo -n "Test: Latence Frontend... "
    start_time=$(date +%s%N)
    curl -s "http://localhost:$FRONTEND_PORT" > /dev/null
    end_time=$(date +%s%N)
    latency=$(( (end_time - start_time) / 1000000 ))
    if [ $latency -lt 2000 ]; then
        pass_test
        echo -e "${GREEN}(${latency}ms)${NC}"
    else
        fail_test
        echo -e "${RED}(${latency}ms)${NC}"
    fi
    
    echo ""
    echo -e "${BLUE}🔍 Tests de sécurité...${NC}"
    echo -e "${CYAN}----------------------${NC}"
    
    # Test CORS
    increment_test
    echo -n "Test: CORS Headers... "
    cors_headers=$(curl -s -I "http://localhost:$BACKEND_PORT/api/v1/tracks" | grep -i "access-control-allow-origin")
    if [ ! -z "$cors_headers" ]; then
        pass_test
    else
        fail_test
    fi
    
    # Test Content-Type
    increment_test
    echo -n "Test: Content-Type JSON... "
    content_type=$(curl -s -I "http://localhost:$BACKEND_PORT/api/v1/tracks" | grep -i "content-type.*json")
    if [ ! -z "$content_type" ]; then
        pass_test
    else
        fail_test
    fi
}

# Vérifier les dépendances
check_dependencies() {
    echo -e "${BLUE}🔍 Vérification des dépendances...${NC}"
    
    # Vérifier curl
    if ! command -v curl &> /dev/null; then
        echo -e "${RED}❌ curl n'est pas installé${NC}"
        exit 1
    fi
    
    # Vérifier jq
    if ! command -v jq &> /dev/null; then
        echo -e "${RED}❌ jq n'est pas installé${NC}"
        exit 1
    fi
    
    echo -e "${GREEN}✅ Toutes les dépendances sont installées${NC}"
    echo ""
}

# Fonction principale
main() {
    # Vérifier les dépendances
    check_dependencies
    
    # Attendre que les services démarrent
    echo -e "${YELLOW}⏳ Attente du démarrage des services...${NC}"
    sleep 5
    
    # Exécuter les tests
    run_tests
    
    # Afficher le résumé
    show_summary
}

# Exécuter le script principal
main "$@" 