<?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
    {
        Schema::create('ethnic_groups', function (Blueprint $table) {
            $table->id();
            $table->string('name');
            $table->string('country_code', 3)->index();
            $table->string('languages')->nullable();
            $table->text('description')->nullable();
            $table->timestamps();
        });

        Schema::create('clans', function (Blueprint $table) {
            $table->id();
            $table->unsignedBigInteger('ethnic_group_id');
            $table->string('name');
            $table->text('description')->nullable();
            $table->timestamps();

            $table->foreign('ethnic_group_id', 'fk_clans_ethnic_group_id')
                  ->references('id')->on('ethnic_groups')
                  ->cascadeOnDelete();
        });

        Schema::table('families', function (Blueprint $table) {
            if (!Schema::hasColumn('families', 'ethnic_group_id')) {
                $table->unsignedBigInteger('ethnic_group_id')->nullable()->after('created_by');
                $table->foreign('ethnic_group_id', 'fk_families_ethnic_group_id')
                      ->references('id')->on('ethnic_groups')
                      ->nullOnDelete();
            }
            if (!Schema::hasColumn('families', 'clan_id')) {
                $table->unsignedBigInteger('clan_id')->nullable()->after('ethnic_group_id');
                $table->foreign('clan_id', 'fk_families_clan_id')
                      ->references('id')->on('clans')
                      ->nullOnDelete();
            }
        });
    }

    public function down(): void
    {
        Schema::table('families', function (Blueprint $table) {
            if (Schema::hasColumn('families', 'clan_id')) {
                $table->dropForeign('fk_families_clan_id');
                $table->dropColumn('clan_id');
            }
            if (Schema::hasColumn('families', 'ethnic_group_id')) {
                $table->dropForeign('fk_families_ethnic_group_id');
                $table->dropColumn('ethnic_group_id');
            }
        });
        Schema::dropIfExists('clans');
        Schema::dropIfExists('ethnic_groups');
    }
};
