#!/bin/bash
# Script pour appliquer les migrations SQL sur la base de données de labo
# Usage: ./scripts/apply_migrations_lab.sh

set -e

# Couleurs pour les messages
GREEN='\033[0;32m'
YELLOW='\033[0;33m'
RED='\033[0;31m'
NC='\033[0m' # No Color

# DSN de la base de données de labo
VEZA_LAB_DSN="${VEZA_LAB_DSN:-postgres://veza:veza_password@localhost:5432/veza_lab?sslmode=disable}"

echo -e "${GREEN}📦 Application des migrations sur veza_lab...${NC}"
echo -e "${YELLOW}DSN: ${VEZA_LAB_DSN}${NC}"
echo ""

# Vérifier que psql est disponible
if ! command -v psql &> /dev/null; then
    echo -e "${RED}❌ psql n'est pas installé. Installez PostgreSQL client.${NC}"
    exit 1
fi

# Extraire les composants de l'URL pour psql
# Format: postgres://user:password@host:port/database?params
if [[ $VEZA_LAB_DSN =~ postgres://([^:]+):([^@]+)@([^:]+):([^/]+)/([^?]+) ]]; then
    DB_USER="${BASH_REMATCH[1]}"
    DB_PASS="${BASH_REMATCH[2]}"
    DB_HOST="${BASH_REMATCH[3]}"
    DB_PORT="${BASH_REMATCH[4]}"
    DB_NAME="${BASH_REMATCH[5]}"
else
    echo -e "${RED}❌ Format de DSN invalide: ${VEZA_LAB_DSN}${NC}"
    exit 1
fi

# Exporter le mot de passe pour psql
export PGPASSWORD="${DB_PASS}"

# Répertoire des migrations
MIGRATIONS_DIR="$(dirname "$0")/../migrations"

if [ ! -d "$MIGRATIONS_DIR" ]; then
    echo -e "${RED}❌ Répertoire migrations non trouvé: ${MIGRATIONS_DIR}${NC}"
    exit 1
fi

# Appliquer les migrations dans l'ordre
echo -e "${GREEN}🔧 Application des migrations...${NC}"

for migration_file in "$MIGRATIONS_DIR"/*.sql; do
    if [ -f "$migration_file" ]; then
        migration_name=$(basename "$migration_file")
        echo -e "${YELLOW}  → ${migration_name}${NC}"
        
        if psql -h "$DB_HOST" -p "$DB_PORT" -U "$DB_USER" -d "$DB_NAME" -f "$migration_file" > /dev/null 2>&1; then
            echo -e "${GREEN}    ✅ Migration appliquée${NC}"
        else
            # Vérifier si l'erreur est due à "already exists" (OK)
            if psql -h "$DB_HOST" -p "$DB_PORT" -U "$DB_USER" -d "$DB_NAME" -f "$migration_file" 2>&1 | grep -q "already exists"; then
                echo -e "${YELLOW}    ⚠️  Tables déjà existantes (OK)${NC}"
            else
                echo -e "${RED}    ❌ Erreur lors de l'application${NC}"
                psql -h "$DB_HOST" -p "$DB_PORT" -U "$DB_USER" -d "$DB_NAME" -f "$migration_file"
                exit 1
            fi
        fi
    fi
done

echo ""
echo -e "${GREEN}✅ Toutes les migrations ont été appliquées${NC}"

# Vérifier que les tables existent
echo ""
echo -e "${GREEN}🔍 Vérification des tables créées...${NC}"
TABLES=$(psql -h "$DB_HOST" -p "$DB_PORT" -U "$DB_USER" -d "$DB_NAME" -t -c "SELECT COUNT(*) FROM information_schema.tables WHERE table_schema = 'public' AND table_name IN ('stream_jobs', 'stream_segments');")

if [ "$TABLES" -eq "2" ]; then
    echo -e "${GREEN}✅ Tables stream_jobs et stream_segments présentes${NC}"
else
    echo -e "${YELLOW}⚠️  Certaines tables peuvent être manquantes (vérifiez manuellement)${NC}"
fi

# Nettoyer
unset PGPASSWORD

