<?php

declare(strict_types=1);

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

return new class extends Migration
{
    public function up(): void
    {
        /*
         | Gapless, race-free tag numbering.
         |
         | `MAX(asset_tag) + 1` produces duplicates under concurrent creation:
         | two requests can both read the same MAX before either commits. A
         | single counter row, locked with SELECT ... FOR UPDATE inside the
         | creating transaction (see AssetTagGenerator), costs one extra query
         | and makes duplicate tags impossible rather than merely unlikely.
         |
         | `scope_key` is either 'global' or a category code, depending on the
         | `asset_tag_scope` setting — one row per counter the format actually
         | needs, not one row per asset.
         */
        Schema::create('asset_tag_sequences', function (Blueprint $table): void {
            $table->id();
            $table->string('scope_key', 40)->unique();
            $table->unsignedInteger('last_number')->default(0);
            $table->timestamps();
        });
    }

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