<?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_reservation_movements', function (Blueprint $table) {
            $table->id();
            $table->foreignId('tenant_id')->constrained('tenants')->cascadeOnDelete();
            $table->foreignId('warehouse_id')->constrained('inventory_warehouses')->restrictOnDelete();
            $table->foreignId('item_id')->constrained('inventory_items')->restrictOnDelete();
            $table->uuid('reservation_public_id');
            $table->string('entry_type', 32);
            $table->decimal('quantity', 24, 8);
            $table->timestamp('expires_at')->nullable();
            $table->uuid('correlation_id')->nullable();
            $table->string('idempotency_key', 191)->nullable();
            $table->string('idempotency_source', 64)->default('default');
            $table->string('source_type', 80)->nullable();
            $table->unsignedBigInteger('source_id')->nullable();
            $table->foreignId('actor_user_id')->nullable()->constrained('users')->nullOnDelete();
            $table->json('metadata')->nullable();
            $table->timestamp('created_at')->useCurrent();

            $table->index(['tenant_id', 'warehouse_id', 'item_id', 'id'], 'inv_res_mov_slice_seq');
            $table->index(['tenant_id', 'reservation_public_id', 'id'], 'inv_res_mov_res_seq');
            $table->index(['tenant_id', 'idempotency_key', 'idempotency_source'], 'inv_res_mov_idem');
        });

        Schema::create('inventory_reservation_idempotency_keys', function (Blueprint $table) {
            $table->id();
            $table->foreignId('tenant_id')->constrained('tenants')->cascadeOnDelete();
            $table->string('idempotency_key', 191);
            $table->string('idempotency_source', 64)->default('default');
            $table->unsignedBigInteger('first_reservation_movement_id');
            $table->json('result_payload');
            $table->timestamp('created_at')->useCurrent();

            $table->unique(['tenant_id', 'idempotency_key', 'idempotency_source'], 'inv_res_idem_uq');
            $table->foreign('first_reservation_movement_id', 'inv_res_idem_mov_fk')
                ->references('id')->on('inventory_reservation_movements')->cascadeOnDelete();
        });
    }

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