<?php

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

class AddForeignKeysAndReorderLocationColumnsToClientsTable extends Migration
{
    public function up(): void
    {
        // Reordenar columna name
        DB::statement("ALTER TABLE clients MODIFY COLUMN name VARCHAR(191) NOT NULL AFTER status");

        Schema::table('clients', function (Blueprint $table) {
            // Crear o modificar columnas como NOT NULL
            if (!Schema::hasColumn('clients', 'country_id')) {
                $table->unsignedBigInteger('country_id')->after('rtn');
            } else {
                $table->unsignedBigInteger('country_id')->change();
            }

            if (!Schema::hasColumn('clients', 'state_id')) {
                $table->unsignedBigInteger('state_id')->after('country_id');
            } else {
                $table->unsignedBigInteger('state_id')->change();
            }

            if (!Schema::hasColumn('clients', 'city_id')) {
                $table->unsignedBigInteger('city_id')->after('state_id');
            } else {
                $table->unsignedBigInteger('city_id')->change();
            }
        });

        // Agregar claves foráneas con RESTRICT
        Schema::table('clients', function (Blueprint $table) {
            $table->foreign('country_id')->references('id')->on('countries')->restrictOnDelete();
            $table->foreign('state_id')->references('id')->on('states')->restrictOnDelete();
            $table->foreign('city_id')->references('id')->on('cities')->restrictOnDelete();
        });
    }

    public function down(): void
    {
        Schema::table('clients', function (Blueprint $table) {
            $table->dropForeign(['country_id']);
            $table->dropForeign(['state_id']);
            $table->dropForeign(['city_id']);

            $table->dropColumn(['country_id', 'state_id', 'city_id']);
        });
    }
}
