<?php

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

/**
 * Scotland local authorities (councils) and their areas/suburbs — reference data
 * seeded from "Council & Suburbs.ods" (see ScotlandAreasSeeder). A care setting
 * links to an area; its local authority is the area's council. This backs the
 * "Area → Council MUST be X" cascade and area/council filtering.
 */
return new class extends Migration {
    public function up(): void
    {
        Schema::create('councils', function (Blueprint $table) {
            $table->id();
            $table->string('name')->unique();
            $table->timestamps();
        });

        Schema::create('areas', function (Blueprint $table) {
            $table->id();
            $table->foreignId('council_id')->constrained()->cascadeOnDelete();
            $table->string('name')->index();
            $table->timestamps();

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

        Schema::table('care_settings', function (Blueprint $table) {
            if (! Schema::hasColumn('care_settings', 'area_id')) {
                $table->foreignId('area_id')->nullable()->after('institution_id')
                    ->constrained()->nullOnDelete();
            }
        });
    }

    public function down(): void
    {
        Schema::table('care_settings', function (Blueprint $table) {
            $table->dropConstrainedForeignId('area_id');
        });

        Schema::dropIfExists('areas');
        Schema::dropIfExists('councils');
    }
};
