<?php

use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;

return new class extends Migration
{
    /**
     * Run the migrations.
     */
    public function up(): void
    {
        // 1. Aggiorna tabelle millesimali esistenti
        Schema::table('tabelle_millesimali', function (Blueprint $table) {
            // Rinomina la colonna esistente
            $table->renameColumn('nome_tabella_millesimale', 'nome_tabella');
            
            // Aggiungi nuove colonne
            $table->string('codice_tabella')->nullable()->after('nome_tabella');
            $table->enum('tipo_tabella', [
                'proprieta', 'riscaldamento', 'ascensore', 'scale', 'pulizie', 
                'antenna_tv', 'portineria', 'cortile', 'custom', 'temporanea'
            ])->default('custom')->after('codice_tabella');
            $table->boolean('attiva')->default(true)->after('descrizione');
            $table->boolean('temporanea')->default(false)->after('attiva');
            $table->date('validita_da')->nullable()->after('temporanea');
            $table->date('validita_a')->nullable()->after('validita_da');
            $table->decimal('totale_millesimi', 10, 4)->default(1000.0000)->after('validita_a');
            $table->json('configurazione')->nullable()->after('totale_millesimi');
            $table->unsignedBigInteger('created_by')->nullable()->after('configurazione');
            $table->softDeletes()->after('updated_at');
            
            // Aggiungi foreign keys e indexes
            $table->foreign('created_by')->references('id')->on('users')->onDelete('set null');
            $table->index(['stabile_id', 'tipo_tabella']);
            $table->index(['stabile_id', 'attiva']);
        });

        // 2. Verifica se dettaglio_millesimi esiste, altrimenti creala
        if (!Schema::hasTable('dettaglio_millesimi')) {
            Schema::create('dettaglio_millesimi', function (Blueprint $table) {
                $table->id();
                $table->unsignedBigInteger('tabella_millesimale_id');
                $table->unsignedBigInteger('unita_immobiliare_id');
                $table->decimal('millesimi', 10, 4)->default(0.0000);
                $table->boolean('partecipa')->default(true);
                $table->text('note')->nullable();
                $table->unsignedBigInteger('created_by')->nullable();
                $table->timestamps();
                
                $table->foreign('tabella_millesimale_id')->references('id')->on('tabelle_millesimali')->onDelete('cascade');
                $table->foreign('unita_immobiliare_id')->references('id')->on('unita_immobiliari')->onDelete('cascade');
                $table->foreign('created_by')->references('id')->on('users')->onDelete('set null');
                
                $table->unique(['tabella_millesimale_id', 'unita_immobiliare_id'], 'unique_tabella_unita');
                $table->index('millesimi');
            });
        } else {
            // Aggiorna dettaglio_millesimi esistente se necessario
            Schema::table('dettaglio_millesimi', function (Blueprint $table) {
                if (!Schema::hasColumn('dettaglio_millesimi', 'partecipa')) {
                    $table->boolean('partecipa')->default(true)->after('millesimi');
                }
                if (!Schema::hasColumn('dettaglio_millesimi', 'note')) {
                    $table->text('note')->nullable()->after('partecipa');
                }
                if (!Schema::hasColumn('dettaglio_millesimi', 'created_by')) {
                    $table->unsignedBigInteger('created_by')->nullable()->after('note');
                    $table->foreign('created_by')->references('id')->on('users')->onDelete('set null');
                }
            });
        }
    }

    /**
     * Reverse the migrations.
     */
    public function down(): void
    {
        Schema::table('tabelle_millesimali', function (Blueprint $table) {
            $table->dropForeign(['created_by']);
            $table->dropIndex(['stabile_id_tipo_tabella_index']);
            $table->dropIndex(['stabile_id_attiva_index']);
            
            $table->dropColumn([
                'codice_tabella', 'tipo_tabella', 'attiva', 'temporanea',
                'validita_da', 'validita_a', 'totale_millesimi', 
                'configurazione', 'created_by', 'deleted_at'
            ]);
            
            $table->renameColumn('nome_tabella', 'nome_tabella_millesimale');
        });
        
        if (Schema::hasTable('dettaglio_millesimi')) {
            Schema::dropIfExists('dettaglio_millesimi');
        }
    }
};
