#!/bin/bash
# =============================================================================
# IDS - Applica Migrazioni Database (con Version Tracking)
# =============================================================================
# Sistema intelligente di migrazioni:
# - Controlla versione corrente database
# - Applica SOLO migrazioni mancanti (più veloce!)
# - Aggiorna versione dopo ogni migrazione
# =============================================================================

set -e

SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
MIGRATIONS_DIR="$SCRIPT_DIR/migrations"
IDS_DIR="$(dirname "$SCRIPT_DIR")"
DEPLOYMENT_MIGRATIONS_DIR="$IDS_DIR/deployment/migrations"

# Carica variabili ambiente ed esportale
if [ -f "$IDS_DIR/.env" ]; then
    set -a
    source "$IDS_DIR/.env"
    set +a
fi

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

echo -e "${BLUE}🗄️  Sistema Migrazioni Database (Versioned)${NC}"

# Verifica DATABASE_URL
if [ -z "$DATABASE_URL" ]; then
    echo -e "${RED}❌ DATABASE_URL non impostato${NC}"
    echo -e "${YELLOW}   File .env non trovato o DATABASE_URL mancante${NC}"
    exit 1
fi

# Crea directory migrations se non esiste
mkdir -p "$MIGRATIONS_DIR"

# =============================================================================
# STEP 1: Inizializza tracking versione (se necessario)
# =============================================================================
echo -e "${CYAN}📋 Verifica sistema versioning...${NC}"

# Esegue 000_init_schema_version.sql (idempotente)
INIT_MIGRATION="$MIGRATIONS_DIR/000_init_schema_version.sql"
if [ -f "$INIT_MIGRATION" ]; then
    psql "$DATABASE_URL" -f "$INIT_MIGRATION" -q
    echo -e "${GREEN}✅ Sistema versioning attivo${NC}"
else
    echo -e "${YELLOW}⚠️  Migration 000_init_schema_version.sql non trovata${NC}"
    echo -e "${YELLOW}   Creazione tabella schema_version...${NC}"
    
    psql "$DATABASE_URL" << 'EOF' -q
    CREATE TABLE IF NOT EXISTS schema_version (
        id INTEGER PRIMARY KEY DEFAULT 1,
        version INTEGER NOT NULL DEFAULT 0,
        applied_at TIMESTAMP NOT NULL DEFAULT NOW(),
        description TEXT
    );
    INSERT INTO schema_version (id, version, description)
    SELECT 1, 0, 'Initial schema version tracking'
    WHERE NOT EXISTS (SELECT 1 FROM schema_version WHERE id = 1);
EOF
    echo -e "${GREEN}✅ Tabella schema_version creata${NC}"
fi

# =============================================================================
# STEP 2: Leggi versione corrente database
# =============================================================================
CURRENT_VERSION=$(psql "$DATABASE_URL" -tAc "SELECT COALESCE(version, 0) FROM schema_version WHERE id = 1;" 2>/dev/null || echo "0")
echo -e "${CYAN}📊 Versione database corrente: ${YELLOW}${CURRENT_VERSION}${NC}"

# =============================================================================
# STEP 3: Trova migrazioni da applicare
# =============================================================================
# Formato migrazioni: 001_description.sql, 002_another.sql, etc.
# Cerca in ENTRAMBE le cartelle: database-schema/migrations E deployment/migrations
MIGRATIONS_TO_APPLY=()

# Combina migrations da entrambe le cartelle e ordina per numero
ALL_MIGRATIONS=""
if [ -d "$MIGRATIONS_DIR" ]; then
    ALL_MIGRATIONS+=$(find "$MIGRATIONS_DIR" -name "[0-9][0-9][0-9]_*.sql" 2>/dev/null || true)
fi
if [ -d "$DEPLOYMENT_MIGRATIONS_DIR" ]; then
    if [ -n "$ALL_MIGRATIONS" ]; then
        ALL_MIGRATIONS+=$'\n'
    fi
    ALL_MIGRATIONS+=$(find "$DEPLOYMENT_MIGRATIONS_DIR" -name "[0-9][0-9][0-9]_*.sql" 2>/dev/null || true)
fi

# Ordina le migrations per nome file (NNN_*.sql) estraendo il basename
SORTED_MIGRATIONS=$(echo "$ALL_MIGRATIONS" | grep -v '^$' | while read f; do echo "$(basename "$f"):$f"; done | sort | cut -d':' -f2)

for migration_file in $SORTED_MIGRATIONS; do
    MIGRATION_NAME=$(basename "$migration_file")
    
    # Estrai numero versione dal nome file (001, 002, etc.)
    MIGRATION_VERSION=$(echo "$MIGRATION_NAME" | sed 's/^\([0-9]\{3\}\)_.*/\1/' | sed 's/^0*//')
    
    # Se versione vuota (000), salta
    if [ -z "$MIGRATION_VERSION" ]; then
        continue
    fi
    
    # Se migrazione > versione corrente, aggiungila
    if [ "$MIGRATION_VERSION" -gt "$CURRENT_VERSION" ]; then
        MIGRATIONS_TO_APPLY+=("$migration_file:$MIGRATION_VERSION:$MIGRATION_NAME")
    fi
done

# =============================================================================
# STEP 4: Applica migrazioni mancanti
# =============================================================================
if [ ${#MIGRATIONS_TO_APPLY[@]} -eq 0 ]; then
    echo -e "${GREEN}✅ Database già aggiornato (nessuna migrazione da applicare)${NC}"
    exit 0
fi

echo -e "${BLUE}📋 Trovate ${#MIGRATIONS_TO_APPLY[@]} migrazioni da applicare${NC}"
echo ""

for migration_info in "${MIGRATIONS_TO_APPLY[@]}"; do
    IFS=':' read -r migration_file migration_version migration_name <<< "$migration_info"
    
    echo -e "${BLUE}🔄 Applicando migrazione ${migration_version}: ${CYAN}${migration_name}${NC}"
    
    # Applica migrazione
    if psql "$DATABASE_URL" -f "$migration_file" -q 2>&1 | tee /tmp/migration_output.log | grep -qiE "error|fatal"; then
        echo -e "${RED}❌ Errore in migrazione ${migration_version}${NC}"
        cat /tmp/migration_output.log
        exit 1
    fi
    
    # Aggiorna versione nel database
    DESCRIPTION=$(head -n 5 "$migration_file" | grep -E "^--.*Migration" | sed 's/^--.*Migration [0-9]*: //' || echo "Migration $migration_version")
    
    psql "$DATABASE_URL" -q << EOF
    UPDATE schema_version 
    SET version = $migration_version,
        applied_at = NOW(),
        description = '$DESCRIPTION'
    WHERE id = 1;
EOF
    
    echo -e "${GREEN}   ✅ Migrazione ${migration_version} applicata con successo${NC}"
    echo ""
done

# =============================================================================
# STEP 5: Verifica versione finale
# =============================================================================
FINAL_VERSION=$(psql "$DATABASE_URL" -tAc "SELECT version FROM schema_version WHERE id = 1;")
echo -e "${GREEN}╔═══════════════════════════════════════════════╗${NC}"
echo -e "${GREEN}║   ✅ MIGRAZIONI COMPLETATE                    ║${NC}"
echo -e "${GREEN}╚═══════════════════════════════════════════════╝${NC}"
echo -e "${CYAN}📊 Versione database: ${YELLOW}${CURRENT_VERSION}${CYAN} → ${GREEN}${FINAL_VERSION}${NC}"
echo ""
