<?php

use App\Domains\Catalog\Enums\InventoryPolicy;
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('inventories', function (Blueprint $table): void {
            $table->id();
            $table->unsignedBigInteger('sold_units')->default(0);
            $table->unsignedInteger('reserved_stock')->default(0);
            $table->unsignedInteger('real_stock')->default(0);
        });

        Schema::create('catalog_items', function (Blueprint $table): void {
            $table->id();
            $table->string('tenant_code');
            $table->foreignId('category_id')->nullable()->constrained('categorias')->nullOnDelete();
            $table->foreignId('brand_id')->nullable()->constrained('brands')->nullOnDelete();
            $table->foreignId('inventory_id')->nullable()->unique()->constrained('inventories')->restrictOnDelete();
            $table->string('slug');
            $table->string('nombre');
            $table->text('descripcion')->nullable();
            $table->decimal('precio', 10, 2);
            $table->enum('inventory_policy', InventoryPolicy::values())
                ->default(InventoryPolicy::Tracked->value);
            $table->boolean('has_tickets')->default(false);
            $table->dateTime('maximum_use_date')->nullable();
            $table->dateTime('minimum_use_date')->nullable();

            $table->foreign('tenant_code')
                ->references('codigo')
                ->on('tenants')
                ->cascadeOnUpdate()
                ->restrictOnDelete();

            $table->unique(['tenant_code', 'slug']);
        });
    }

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