<?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('wards', function (Blueprint $table) {
            $table->id();

            // parent district (always helpful for filtering)
            $table->foreignId('district_id')
                ->constrained('districts')
                ->cascadeOnDelete();

            // Exactly ONE of these should be set
            $table->foreignId('upazila_id')
                ->nullable()
                ->constrained('upazilas')
                ->nullOnDelete();

            $table->foreignId('city_id')
                ->nullable()
                ->constrained('cities')
                ->nullOnDelete();

            $table->unsignedSmallInteger('ward_no'); // store numeric ward no

            $table->string('name_bn')->nullable(); // optional: "ওয়ার্ড ১"
            $table->string('name_en')->nullable(); // optional: "Ward 1"

            $table->timestamps();

            // Uniqueness: ward_no unique within a city or within an upazila
            $table->unique(['city_id', 'ward_no']);
            $table->unique(['upazila_id', 'ward_no']);

            $table->index(['district_id']);
            $table->index(['city_id']);
            $table->index(['upazila_id']);
        });
    }

    public function down(): void
    {
        Schema::dropIfExists('wards');
    }
};
