<?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
    {
        Schema::create('subentri_unita', function (Blueprint $table) {
            $table->id();
            $table->unsignedBigInteger('unita_immobiliare_id');
            $table->unsignedBigInteger('soggetto_precedente_id')->nullable();
            $table->unsignedBigInteger('soggetto_nuovo_id');
            
            // Dati subentro
            $table->date('data_subentro');
            $table->enum('tipo_subentro', ['vendita', 'eredita', 'donazione', 'locazione', 'comodato']);
            $table->decimal('quota_precedente', 5, 4)->default(1.0000);
            $table->decimal('quota_nuova', 5, 4)->default(1.0000);
            
            // Documenti
            $table->string('numero_atto', 100)->nullable();
            $table->date('data_atto')->nullable();
            $table->string('notaio', 200)->nullable();
            $table->decimal('prezzo_vendita', 12, 2)->nullable();
            
            // Stati
            $table->enum('stato_subentro', ['proposto', 'in_corso', 'completato', 'annullato'])->default('proposto');
            $table->timestamp('data_completamento')->nullable();
            
            // Automazioni
            $table->boolean('ripartizioni_aggiornate')->default(false);
            $table->boolean('comunicazioni_inviate')->default(false);
            
            // Note e allegati
            $table->text('note')->nullable();
            $table->json('allegati')->nullable();
            
            $table->timestamps();
            $table->unsignedBigInteger('created_by')->nullable();
            
            // Foreign keys
            $table->foreign('unita_immobiliare_id')->references('id')->on('unita_immobiliari')->onDelete('cascade');
            $table->foreign('soggetto_precedente_id')->references('id')->on('soggetti')->onDelete('set null');
            $table->foreign('soggetto_nuovo_id')->references('id')->on('soggetti')->onDelete('cascade');
            $table->foreign('created_by')->references('id')->on('users')->onDelete('set null');
            
            // Indexes
            $table->index('unita_immobiliare_id', 'idx_subentri_unita');
            $table->index('data_subentro', 'idx_subentri_data');
            $table->index('stato_subentro', 'idx_subentri_stato');
            $table->index('tipo_subentro');
        });
    }

    /**
     * Reverse the migrations.
     */
    public function down(): void
    {
        Schema::dropIfExists('subentri_unita');
    }
};
