<?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('geo_countries', function (Blueprint $table) {
            $table->id();
            $table->string('code', 3)->unique();
            $table->json('name');
            $table->boolean('is_active')->default(true);
            $table->unsignedSmallInteger('sort_order')->default(0);
            $table->timestamps();

            $table->index(['is_active', 'sort_order'], 'geo_countries_active_sort');
        });

        Schema::create('geo_regions', function (Blueprint $table) {
            $table->id();
            $table->foreignId('country_id')->constrained('geo_countries')->cascadeOnDelete();
            $table->foreignId('tenant_id')->nullable()->constrained('tenants')->cascadeOnDelete();
            $table->json('name');
            $table->boolean('is_active')->default(true);
            $table->unsignedSmallInteger('sort_order')->default(0);
            $table->timestamps();

            $table->index(['country_id', 'is_active', 'sort_order'], 'geo_regions_country_sort');
            $table->index(['tenant_id', 'country_id'], 'geo_regions_tenant_country');
        });

        Schema::create('geo_cities', function (Blueprint $table) {
            $table->id();
            $table->foreignId('region_id')->constrained('geo_regions')->cascadeOnDelete();
            $table->foreignId('tenant_id')->nullable()->constrained('tenants')->cascadeOnDelete();
            $table->json('name');
            $table->boolean('is_active')->default(true);
            $table->unsignedSmallInteger('sort_order')->default(0);
            $table->timestamps();

            $table->index(['region_id', 'is_active', 'sort_order'], 'geo_cities_region_sort');
            $table->index(['tenant_id', 'region_id'], 'geo_cities_tenant_region');
        });
    }

    public function down(): void
    {
        Schema::dropIfExists('geo_cities');
        Schema::dropIfExists('geo_regions');
        Schema::dropIfExists('geo_countries');
    }
};
