<?php

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

return new class extends Migration
{
    /**
     * Backfill `region` = 'main' for any pre-existing rows where it is NULL.
     * Without this, ordering can collide between legacy NULL rows and new
     * 'main' rows on the same entity, since both buckets share the default
     * region in the read scope but the admin reorder UI only knows about
     * 'main'-region rows.
     */
    public function up(): void
    {
        if (!Schema::hasTable('entity_blocks') || !Schema::hasColumn('entity_blocks', 'region')) {
            return;
        }

        DB::table('entity_blocks')
            ->whereNull('region')
            ->update(['region' => 'main']);
    }

    public function down(): void
    {
        // Intentionally not reversed — we don't track which rows were
        // originally NULL.
    }
};
