<?php

use App\Domains\Cart\Models\CartItem;
use App\Domains\Catalog\Services\StockReservationService;
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::table('carritos', function (Blueprint $table): void {
            $table->string('origin')->default('user')->after('status');
        });

        Schema::create('stock_reservations', function (Blueprint $table): void {
            $table->id();
            $table->foreignId('inventory_id')->constrained('inventories')->restrictOnDelete();
            $table->foreignId('cart_item_id')->nullable()->constrained('carrito_items')->nullOnDelete();
            $table->foreignId('purchase_id')->nullable()->constrained('compras')->cascadeOnDelete();
            $table->unsignedInteger('quantity');
            $table->string('status')->default('active');
            $table->dateTime('expires_at')->nullable();
            $table->dateTime('committed_at')->nullable();
            $table->dateTime('released_at')->nullable();
            $table->timestamps();

            $table->unique(['cart_item_id', 'inventory_id']);
            $table->index(['purchase_id', 'status']);
            $table->index(['status', 'expires_at']);
        });

        CartItem::query()
            ->whereHas('cart', fn ($query) => $query->where('status', 'active'))
            ->with([
                'catalogItem.inventory',
                'catalogItem.bundleComponents.catalogItem.inventory',
                'catalogItem.bundleComponents.variant.inventory',
                'variant.inventory',
                'variant.catalogItem',
            ])
            ->eachById(function (CartItem $cartItem): void {
                $selection = $cartItem->selectedItem();
                if ($selection !== null) {
                    app(StockReservationService::class)->ensure($cartItem, $selection);
                }
            });
    }

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

        Schema::table('carritos', function (Blueprint $table): void {
            $table->dropColumn('origin');
        });
    }
};
