#!/bin/bash
# Deploy migration 013 su MySQL 8.0 (idempotente)
# Uso: bash deploy_013.sh  (da /var/www/nis2-agile)
# Richiede: DB_NAME, DB_USER, DB_PASS dal .env o da variabili d'ambiente

set -e

SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
ENV_FILE="$(dirname "$SCRIPT_DIR")/.env"

# Carica .env se presente
if [ -f "$ENV_FILE" ]; then
    export $(grep -v '^#' "$ENV_FILE" | grep -E '^DB_' | xargs)
fi

DB_NAME="${DB_NAME:-nis2_agile_db}"
DB_USER="${DB_USER:-nis2_user}"
DB_PASS="${DB_PASS:-}"
DB_HOST="${DB_HOST:-localhost}"

MYSQL="mysql -h$DB_HOST -u$DB_USER -p$DB_PASS $DB_NAME"

add_column_if_missing() {
    local table=$1 column=$2 definition=$3 after=$4
    EXISTS=$($MYSQL -sN -e "
        SELECT COUNT(*) FROM INFORMATION_SCHEMA.COLUMNS
        WHERE TABLE_SCHEMA='$DB_NAME' AND TABLE_NAME='$table' AND COLUMN_NAME='$column';
    ")
    if [ "$EXISTS" -eq 0 ]; then
        echo "  + ADD COLUMN $table.$column"
        $MYSQL -e "ALTER TABLE $table ADD COLUMN $column $definition AFTER $after;"
    else
        echo "  . SKIP $table.$column (già presente)"
    fi
}

echo "=== Migration 013: License Ext ==="

# invites
add_column_if_missing invites max_users_per_org "SMALLINT UNSIGNED NULL DEFAULT NULL" max_uses
add_column_if_missing invites price_eur         "DECIMAL(8,2) NULL DEFAULT NULL"     max_users_per_org
add_column_if_missing invites reseller_name     "VARCHAR(128) NULL DEFAULT NULL"      price_eur

# organizations
add_column_if_missing organizations license_max_users "SMALLINT UNSIGNED NULL DEFAULT NULL" license_expires_at

echo "=== Migration 013 completata. ==="
