#!/bin/bash

# Script di gestione database unificato
# Uso: ./manage-database.sh [fresh|migrate|schema]

ACTION=${1:-migrate}
REMOTE_USER="michele"
REMOTE_HOST="192.168.0.43"
REMOTE_PATH="/var/www/netgescon"

case $ACTION in
    fresh)
        echo "🗑️ Database fresh (elimina tutto e ricrea)..."
        ssh $REMOTE_USER@$REMOTE_HOST "cd $REMOTE_PATH && \
            rm -f database/schema/mysql-schema.sql && \
            php artisan migrate:fresh --seed"
        ;;
    migrate)
        echo "🔄 Solo migration incrementali..."
        ssh $REMOTE_USER@$REMOTE_HOST "cd $REMOTE_PATH && \
            rm -f database/schema/mysql-schema.sql && \
            php artisan migrate --force"
        ;;
    schema)
        echo "📊 Genera nuovo schema dopo migration..."
        ssh $REMOTE_USER@$REMOTE_HOST "cd $REMOTE_PATH && \
            php artisan schema:dump --prune"
        ;;
    repair)
        echo "🔧 Ripara database conflittuale..."
        ssh $REMOTE_USER@$REMOTE_HOST "cd $REMOTE_PATH && \
            mysql -u netgescon_user -p -e 'SET FOREIGN_KEY_CHECKS = 0; DROP DATABASE netgescon; CREATE DATABASE netgescon CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci; SET FOREIGN_KEY_CHECKS = 1;' && \
            rm -f database/schema/mysql-schema.sql && \
            php artisan migrate:fresh --seed"
        ;;
    *)
        echo "Uso: $0 [fresh|migrate|schema|repair]"
        echo "  fresh:   Elimina tutto e ricrea database"
        echo "  migrate: Solo migration incrementali (default)"
        echo "  schema:  Genera nuovo schema"
        echo "  repair:  Ripara database conflittuale"
        exit 1
        ;;
esac

echo "✅ Operazione completata!"
