<?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('inventory_categories', function (Blueprint $table) {
            $table->id();
            $table->foreignId('tenant_id')->constrained('tenants')->cascadeOnDelete();
            $table->foreignId('parent_id')->nullable()->constrained('inventory_categories')->nullOnDelete();
            $table->string('code', 120);
            $table->string('name');
            $table->unsignedInteger('sort_order')->default(0);
            $table->boolean('is_active')->default(true);
            $table->timestamp('deactivated_at')->nullable();
            $table->foreignId('created_by')->nullable()->constrained('users')->nullOnDelete();
            $table->foreignId('updated_by')->nullable()->constrained('users')->nullOnDelete();
            $table->timestamps();

            $table->unique(['tenant_id', 'code'], 'inv_cat_tenant_code_uq');
            $table->index(['tenant_id', 'parent_id', 'is_active'], 'inv_cat_tnt_parent_act');
        });

        Schema::create('inventory_items', function (Blueprint $table) {
            $table->id();
            $table->foreignId('tenant_id')->constrained('tenants')->cascadeOnDelete();
            $table->foreignId('parent_item_id')->nullable()->constrained('inventory_items')->nullOnDelete();
            $table->foreignId('inventory_category_id')->nullable()->constrained('inventory_categories')->nullOnDelete();
            $table->foreignId('default_unit_id')->nullable()->constrained('inventory_units')->nullOnDelete();
            $table->string('sku', 120);
            $table->string('barcode', 191)->nullable();
            $table->string('name');
            $table->text('description')->nullable();
            $table->boolean('is_variant')->default(false);
            $table->boolean('is_active')->default(true);
            $table->string('lifecycle_state', 32)->default('draft');
            $table->timestamp('deactivated_at')->nullable();
            $table->foreignId('created_by')->nullable()->constrained('users')->nullOnDelete();
            $table->foreignId('updated_by')->nullable()->constrained('users')->nullOnDelete();
            $table->timestamps();

            $table->unique(['tenant_id', 'sku'], 'inv_item_tenant_sku_uq');
            $table->index(['tenant_id', 'parent_item_id'], 'inv_item_tnt_parent');
            $table->index(['tenant_id', 'barcode'], 'inv_item_tnt_barcode');
            $table->index(['tenant_id', 'is_active', 'lifecycle_state'], 'inv_item_tnt_act_lc');
        });
    }

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