#!/bin/bash

# ============================================================================
# Script Principal - Exécuter TOUS les Tests MVP
# ============================================================================
# Ce script exécute tous les tests (API + E2E) et génère un rapport complet
# ============================================================================

set -euo pipefail

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

REPORT_DIR="test-reports/$(date +%Y%m%d-%H%M%S)"
mkdir -p "$REPORT_DIR"

log_info() {
    echo -e "${BLUE}[INFO]${NC} $1"
}

log_success() {
    echo -e "${GREEN}[✓]${NC} $1"
}

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

log_warning() {
    echo -e "${YELLOW}[!]${NC} $1"
}

# ============================================================================
# Main
# ============================================================================

main() {
    echo "============================================================================"
    echo "TESTS EXHAUSTIFS MVP - EXÉCUTION COMPLÈTE"
    echo "============================================================================"
    echo ""
    echo "Report directory: $REPORT_DIR"
    echo ""
    
    # 1. Setup environnement
    log_info "Step 1: Setting up environment..."
    ./scripts/setup-mvp-test-env.sh > "$REPORT_DIR/setup.log" 2>&1 || log_warning "Setup completed with warnings"
    log_success "Environment setup completed"
    echo ""
    
    # 2. Tests API
    log_info "Step 2: Running API tests..."
    if ./scripts/test-mvp-api.sh > "$REPORT_DIR/api-tests.log" 2>&1; then
        log_success "API tests completed"
    else
        log_error "API tests failed (check $REPORT_DIR/api-tests.log)"
    fi
    echo ""
    
    # 3. Tests E2E
    log_info "Step 3: Running E2E tests..."
    cd apps/web
    if npm run test:e2e -- e2e/mvp-integration.spec.ts > "../../$REPORT_DIR/e2e-tests.log" 2>&1; then
        log_success "E2E tests completed"
    else
        log_error "E2E tests failed (check $REPORT_DIR/e2e-tests.log)"
    fi
    cd ../..
    echo ""
    
    # 4. Générer rapport de bugs
    log_info "Step 4: Generating bug report..."
    ./scripts/generate-bug-report.sh "$REPORT_DIR/bugs.json"
    log_success "Bug report generated"
    echo ""
    
    # 5. Résumé
    echo "============================================================================"
    echo "RÉSUMÉ"
    echo "============================================================================"
    echo ""
    echo "Reports saved to: $REPORT_DIR"
    echo ""
    echo "Files generated:"
    echo "  - setup.log"
    echo "  - api-tests.log"
    echo "  - e2e-tests.log"
    echo "  - bugs.json"
    echo ""
    log_info "Review the logs and bug report to identify issues"
}

main

