<?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
    {
        /*
         | Asset classification, as a self-referencing hierarchy capped at two
         | levels in the application (Laptop > Ultrabook, not deeper).
         |
         | Categories and subcategories have identical attributes, so a
         | self-reference avoids a duplicate table and lets the hierarchy deepen
         | later without a migration. The depth cap lives in validation, where it
         | can be relaxed without touching the schema.
         |
         | `code` is not decoration: it becomes the middle segment of every
         | generated asset tag (AUM-LAP-0042), which is why it is short,
         | mandatory and unique.
         */
        Schema::create('asset_categories', function (Blueprint $table): void {
            $table->id();

            /*
             | RESTRICT, not CASCADE: deleting a parent category must never
             | silently take its subcategories — and the assets classified under
             | them — with it. The controller refuses and explains instead.
             */
            $table->foreignId('parent_id')
                ->nullable()
                ->constrained('asset_categories')
                ->restrictOnDelete();

            $table->string('name', 100);
            $table->string('code', 10)->unique();

            // Informational, for a future depreciation report.
            $table->unsignedTinyInteger('depreciation_years')->nullable();

            // Pre-fills the warranty end date when an asset of this type is added.
            $table->unsignedSmallInteger('default_warranty_months')->nullable();

            $table->boolean('is_active')->default(true);

            $table->timestamps();
            $table->softDeletes();

            /*
             | Sibling names must be distinct. MySQL treats NULLs as distinct in
             | a unique index, so this constrains subcategories but not roots;
             | root-level uniqueness is enforced in the Form Request, which can
             | see NULL for what it means here.
             */
            $table->unique(['parent_id', 'name']);

            $table->index('is_active');
            $table->index('deleted_at');
        });
    }

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