<?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
    {
        if (! Schema::hasTable('tbl_districts')) {
            Schema::create('tbl_districts', function (Blueprint $table) {
                $table->increments('id_district');

                $table->unsignedInteger('canton_id')->index();
                $table->string('name', 255);

                $table->timestamps();

                $table->unique(['canton_id', 'name']);

                $table->foreign('canton_id')
                    ->references('id_canton')
                    ->on('tbl_cantons')
                    ->cascadeOnUpdate()
                    ->restrictOnDelete();
            });

            return;
        }

        Schema::table('tbl_districts', function (Blueprint $table) {
            if (! Schema::hasColumn('tbl_districts', 'id_district')) {
                $table->increments('id_district');
            }

            if (! Schema::hasColumn('tbl_districts', 'canton_id')) {
                $table->unsignedInteger('canton_id')->index();
            }

            if (! Schema::hasColumn('tbl_districts', 'name')) {
                $table->string('name', 255);
            }

            if (! Schema::hasColumn('tbl_districts', 'created_at')) {
                $table->timestamps();
            }
        });
    }

    public function down(): void
    {
        // No hacemos drop para evitar pérdida de datos.
    }
};
