<?php

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

return new class extends Migration {
    public function up(): void
    {
        // Si existe la tabla legada (sin columna 'id'), la renombramos
        if (Schema::hasTable('gerencias') && !Schema::hasColumn('gerencias', 'id')) {
            \Illuminate\Support\Facades\DB::statement('ALTER TABLE gerencias RENAME TO gerencias_legacy');
        }

        if (!Schema::hasTable('gerencias')) {
            Schema::create('gerencias', function (Blueprint $table) {
                $table->increments('id');
                $table->string('codigo', 50)->unique();
                $table->string('nombre', 255);
                $table->unsignedInteger('direccion_id');
                $table->boolean('activo')->default(true);
                $table->timestamps();

                $table->foreign('direccion_id')->references('id')->on('direcciones')->onDelete('restrict');
            });
        }
    }

    public function down(): void
    {
        Schema::dropIfExists('gerencias');
        // Restaurar tabla legada si existe
        if (Schema::hasTable('gerencias_legacy')) {
            \Illuminate\Support\Facades\DB::statement('ALTER TABLE gerencias_legacy RENAME TO gerencias');
        }
    }
};
