#!/bin/bash
# Script de déploiement en staging pour Veza Platform
# Usage: ./scripts/deploy-staging.sh

set -e

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

# Function to print status
print_status() {
    echo -e "${GREEN}[INFO]${NC} $1"
}

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

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

print_step() {
    echo -e "${BLUE}[STEP]${NC} $1"
}

# Get script directory
SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
PROJECT_ROOT="$(cd "$SCRIPT_DIR/.." && pwd)"

cd "$PROJECT_ROOT"

print_step "🚀 Déploiement en staging - Veza Platform"
echo ""

# Vérifier les variables d'environnement requises
print_step "1/6: Vérification des variables d'environnement..."

REQUIRED_VARS=(
    "STAGING_JWT_SECRET"
    "STAGING_DB_PASSWORD"
    "STAGING_RABBITMQ_PASSWORD"
)

MISSING_VARS=()
for var in "${REQUIRED_VARS[@]}"; do
    if [ -z "${!var}" ]; then
        MISSING_VARS+=("$var")
    fi
done

if [ ${#MISSING_VARS[@]} -gt 0 ]; then
    print_error "Variables d'environnement manquantes:"
    for var in "${MISSING_VARS[@]}"; do
        echo "  - $var"
    done
    echo ""
    print_warning "Définissez-les avec: export STAGING_JWT_SECRET=... etc."
    exit 1
fi

print_status "✓ Variables d'environnement OK"
echo ""

# Exécuter les tests
print_step "2/6: Exécution des tests..."

print_status "Tests unitaires backend..."
cd veza-backend-api
if ! go test ./internal/... -short -v; then
    print_error "✗ Tests unitaires backend échoués"
    exit 1
fi
cd ..

print_status "Tests unitaires frontend..."
cd apps/web
if ! npm run test:unit 2>/dev/null; then
    print_warning "⚠ Tests unitaires frontend échoués (non bloquant)"
fi
cd "$PROJECT_ROOT"

print_status "✓ Tests terminés"
echo ""

# Build des images Docker
print_step "3/6: Build des images Docker..."

if ! docker-compose -f docker-compose.staging.yml build; then
    print_error "✗ Build des images échoué"
    exit 1
fi

print_status "✓ Images Docker buildées"
echo ""

# Arrêter les services existants
print_step "4/6: Arrêt des services existants..."

docker-compose -f docker-compose.staging.yml down || true

print_status "✓ Services arrêtés"
echo ""

# Déploiement
print_step "5/6: Déploiement..."

if ! docker-compose -f docker-compose.staging.yml up -d; then
    print_error "✗ Déploiement échoué"
    exit 1
fi

print_status "✓ Services démarrés"
echo ""

# Vérification santé
print_step "6/6: Vérification santé..."

print_status "Attente du démarrage des services..."
sleep 15

# Vérifier le backend
BACKEND_URL="${STAGING_API_URL:-http://localhost:8080}"
if curl -f "${BACKEND_URL}/health" > /dev/null 2>&1; then
    print_status "✓ Backend health check OK"
else
    print_warning "⚠ Backend health check échoué (peut prendre plus de temps)"
fi

# Vérifier le frontend
FRONTEND_URL="${STAGING_FRONTEND_URL:-http://localhost:3000}"
if curl -f "${FRONTEND_URL}" > /dev/null 2>&1; then
    print_status "✓ Frontend accessible"
else
    print_warning "⚠ Frontend non accessible (peut prendre plus de temps)"
fi

echo ""
print_status "✅ Déploiement staging réussi!"
echo ""
print_status "Backend: ${BACKEND_URL}"
print_status "Frontend: ${FRONTEND_URL}"
print_status "Swagger UI: ${BACKEND_URL}/swagger/index.html"
echo ""
print_status "Pour voir les logs:"
echo "  docker-compose -f docker-compose.staging.yml logs -f"
echo ""
print_status "Pour arrêter:"
echo "  docker-compose -f docker-compose.staging.yml down"

