<?php

namespace Tests\Feature\Purchase;

use App\Domains\Attachable\Enums\AttachmentType;
use App\Domains\Attachable\Models\Attachment;
use App\Domains\Auth\Models\User;
use App\Domains\Cart\Models\Cart;
use App\Domains\Catalog\Enums\InventoryPolicy;
use App\Domains\Catalog\Models\CatalogItem;
use App\Domains\Catalog\Models\Category;
use App\Domains\Catalog\Models\Inventory;
use App\Domains\Catalog\Models\Variant;
use App\Domains\Purchase\Models\Purchase;
use App\Domains\Purchase\Services\CheckoutService;
use App\Domains\Purchase\Services\UserPurchaseLimitService;
use App\Domains\Tenant\Models\Tenant;
use Illuminate\Foundation\Testing\RefreshDatabase;
use Illuminate\Support\Facades\Queue;
use Illuminate\Support\Str;
use Illuminate\Validation\ValidationException;
use Tests\TestCase;

class StorePurchaseTest extends TestCase
{
    use RefreshDatabase;

    protected function setUp(): void
    {
        parent::setUp();

        Queue::fake();
    }

    public function test_it_starts_checkout_from_cart_with_purchase_item_snapshots(): void
    {
        $tenant = $this->createTenant('sonder', 'Sonder', 'sonder.com.ar');
        $tenant->update([
            'event_title' => 'Sonder Fest',
            'event_location' => 'Test address',
        ]);
        $user = User::factory()->create([
            'email' => 'buyer@example.com',
        ]);
        $category = Category::query()->create([
            'tenant_code' => 'sonder',
            'nombre' => 'Test Category',
        ]);

        $inventory = Inventory::query()->create(['real_stock' => 10]);
        $catalogItem = CatalogItem::query()->create([
            'tenant_code' => 'sonder',
            'category_id' => $category->id,
            'slug' => 'test-product',
            'nombre' => 'Test Product',
            'descripcion' => 'Test',
            'precio' => '50.00',
        ]);

        $variant = Variant::query()->create([
            'catalog_item_id' => $catalogItem->id,
            'inventory_id' => $inventory->id,
        ]);

        $cartResponse = $this->actingAs($user, 'sanctum')
            ->postJson('/api/tenants/sonder/cart/items', [
                'catalog_item_id' => $catalogItem->id,
                'variant_id' => $variant->id,
                'cantidad' => 2,
            ])
            ->assertOk();

        $cartId = $cartResponse->json('data.id');

        $this->assertDatabaseHas('carritos', [
            'id' => $cartId,
            'tenant_codigo' => 'sonder',
            'user_id' => $user->id,
            'status' => 'active',
        ]);

        $response = $this->actingAs($user, 'sanctum')
            ->postJson('/api/tenants/sonder/compras/start-checkout', [
                'cart_id' => $cartId,
            ]);

        $response->assertCreated();
        $response->assertJsonPath('data.cart_id', $cartId);
        $response->assertJsonPath('data.dni', null);
        $response->assertJsonPath('data.telefono', null);
        $response->assertJsonPath('data.nombre_apellido', null);
        $response->assertJsonPath('data.email', null);
        $response->assertJsonPath('data.tenant_codigo', 'sonder');
        $response->assertJsonPath('data.status', Purchase::STATUS_CREATED);
        $response->assertJsonPath('data.items_source', 'purchase');
        $response->assertJsonCount(1, 'data.items');
        $response->assertJsonPath('data.subtotal', '100.00');
        $response->assertJsonPath('data.total', '100.00');

        $purchaseId = $response->json('data.id');

        $this->assertDatabaseHas('compras', [
            'id' => $purchaseId,
            'cart_id' => $cartId,
            'tenant_codigo' => 'sonder',
            'user_id' => $user->id,
            'dni' => null,
            'telefono' => null,
            'nombre_apellido' => null,
            'email' => null,
            'status' => Purchase::STATUS_CREATED,
            'total' => 100,
        ]);
        $this->assertDatabaseHas('compra_items', [
            'compra_id' => $purchaseId,
            'source_catalog_item_id' => $catalogItem->id,
            'source_variant_id' => $variant->id,
            'cantidad' => 2,
            'precio_unitario' => '50.00',
            'total' => '100.00',
        ]);
        $this->assertDatabaseHas('stock_reservations', [
            'inventory_id' => $inventory->id,
            'purchase_id' => $purchaseId,
            'quantity' => 2,
            'status' => 'active',
        ]);
        $this->assertDatabaseHas('carritos', [
            'id' => $cartId,
            'user_id' => $user->id,
            'status' => 'active',
            'origin' => Cart::ORIGIN_USER,
            'current_purchase_id' => $purchaseId,
            'deleted_at' => null,
        ]);
        $this->assertDatabaseHas('carrito_items', [
            'cart_id' => $cartId,
            'catalog_item_id' => $catalogItem->id,
            'variant_id' => $variant->id,
            'cantidad' => 2,
        ]);
        $this->assertDatabaseHas('inventories', [
            'id' => $inventory->id,
            'real_stock' => 10,
            'reserved_stock' => 2,
        ]);

        $this->actingAs($user, 'sanctum')
            ->getJson('/api/tenants/sonder/cart')
            ->assertOk()
            ->assertJsonPath('data.id', $cartId)
            ->assertJsonPath('data.status', 'active')
            ->assertJsonCount(1, 'data.items')
            ->assertJsonPath('data.items.0.cantidad', 2);

        $replacementResponse = $this->actingAs($user, 'sanctum')
            ->postJson('/api/tenants/sonder/compras/start-checkout', [
                'cart_id' => $cartId,
            ])
            ->assertCreated();
        $replacementPurchaseId = $replacementResponse->json('data.id');

        $this->assertDatabaseHas('compras', [
            'id' => $purchaseId,
            'status' => Purchase::STATUS_SUPERSEDED,
        ]);
        $this->assertDatabaseHas('carritos', [
            'id' => $cartId,
            'current_purchase_id' => $replacementPurchaseId,
        ]);
        $this->assertDatabaseHas('stock_reservations', [
            'inventory_id' => $inventory->id,
            'purchase_id' => $replacementPurchaseId,
            'quantity' => 2,
            'status' => 'active',
        ]);
        $this->assertDatabaseHas('inventories', [
            'id' => $inventory->id,
            'reserved_stock' => 2,
        ]);

        $catalogItem->update([
            'nombre' => 'Updated Product',
            'precio' => '75.00',
        ]);

        $this->actingAs($user, 'sanctum')
            ->getJson("/api/tenants/sonder/compras/{$purchaseId}")
            ->assertOk()
            ->assertJsonPath('data.items_source', 'purchase')
            ->assertJsonPath('data.items.0.item_details.nombre', 'Test Product')
            ->assertJsonPath('data.items.0.unit_price', '50.00')
            ->assertJsonPath('data.total', '100.00');
    }

    public function test_it_creates_a_direct_purchase_with_a_technical_checkout_cart(): void
    {
        $this->createTenant('sonder', 'Sonder', 'sonder.com.ar');
        $user = User::factory()->create();
        $variant = $this->createVariantForTenant('sonder', 10, '50.00');

        $response = $this->actingAs($user, 'sanctum')
            ->postJson('/api/tenants/sonder/compras/start-checkout', [
                'direct_items' => [
                    [
                        'catalog_item_id' => $variant->catalog_item_id,
                        'variant_id' => $variant->id,
                        'cantidad' => 3,
                    ],
                ],
            ])
            ->assertCreated()
            ->assertJsonPath('data.items_source', 'purchase')
            ->assertJsonPath('data.items.0.quantity', 3)
            ->assertJsonPath('data.total', '150.00');

        $this->assertDatabaseHas('carritos', [
            'id' => $response->json('data.cart_id'),
            'status' => 'checkout',
            'origin' => Cart::ORIGIN_DIRECT_CHECKOUT,
            'current_purchase_id' => $response->json('data.id'),
        ]);
        $this->assertDatabaseHas('compra_items', [
            'compra_id' => $response->json('data.id'),
            'source_variant_id' => $variant->id,
            'cantidad' => 3,
            'precio_unitario' => '50.00',
            'total' => '150.00',
        ]);
        $this->assertDatabaseHas('stock_reservations', [
            'inventory_id' => $variant->inventory_id,
            'purchase_id' => $response->json('data.id'),
            'quantity' => 3,
            'status' => 'active',
        ]);
        $this->assertDatabaseHas('inventories', [
            'id' => $variant->inventory_id,
            'real_stock' => 10,
            'reserved_stock' => 3,
        ]);

        $this->actingAs($user, 'sanctum')
            ->postJson("/api/tenants/sonder/compras/{$response->json('data.id')}/cancel")
            ->assertOk()
            ->assertJsonPath('data.status', Purchase::STATUS_CANCELLED);

        $this->assertDatabaseHas('stock_reservations', [
            'purchase_id' => $response->json('data.id'),
            'status' => 'released',
        ]);
        $this->assertDatabaseHas('inventories', [
            'id' => $variant->inventory_id,
            'real_stock' => 10,
            'reserved_stock' => 0,
        ]);
    }

    public function test_it_creates_one_direct_purchase_with_multiple_variant_items(): void
    {
        $this->createTenant('sonder', 'Sonder', 'sonder.com.ar');
        $user = User::factory()->create();
        $firstVariant = $this->createVariantForTenant('sonder', 1, '50.00');
        $secondInventory = Inventory::query()->create(['real_stock' => 1]);
        $secondVariant = Variant::query()->create([
            'catalog_item_id' => $firstVariant->catalog_item_id,
            'inventory_id' => $secondInventory->id,
            'precio' => '75.00',
        ]);

        $response = $this->actingAs($user, 'sanctum')
            ->postJson('/api/tenants/sonder/compras/start-checkout', [
                'direct_items' => [
                    [
                        'catalog_item_id' => $firstVariant->catalog_item_id,
                        'variant_id' => $firstVariant->id,
                        'cantidad' => 1,
                    ],
                    [
                        'catalog_item_id' => $secondVariant->catalog_item_id,
                        'variant_id' => $secondVariant->id,
                        'cantidad' => 1,
                    ],
                ],
            ])
            ->assertCreated()
            ->assertJsonPath('data.items_source', 'purchase')
            ->assertJsonCount(2, 'data.items')
            ->assertJsonPath('data.items.0.source_variant_id', $firstVariant->id)
            ->assertJsonPath('data.items.1.source_variant_id', $secondVariant->id)
            ->assertJsonPath('data.total', '125.00');

        $purchaseId = $response->json('data.id');

        $this->assertDatabaseHas('carritos', [
            'id' => $response->json('data.cart_id'),
            'origin' => Cart::ORIGIN_DIRECT_CHECKOUT,
        ]);
        $this->assertDatabaseCount('compra_items', 2);
        $this->assertDatabaseHas('stock_reservations', [
            'inventory_id' => $firstVariant->inventory_id,
            'purchase_id' => $purchaseId,
            'quantity' => 1,
            'status' => 'active',
        ]);
        $this->assertDatabaseHas('stock_reservations', [
            'inventory_id' => $secondVariant->inventory_id,
            'purchase_id' => $purchaseId,
            'quantity' => 1,
            'status' => 'active',
        ]);
        $this->assertDatabaseHas('inventories', [
            'id' => $firstVariant->inventory_id,
            'reserved_stock' => 1,
        ]);
        $this->assertDatabaseHas('inventories', [
            'id' => $secondInventory->id,
            'reserved_stock' => 1,
        ]);
    }

    public function test_multi_item_direct_purchase_rolls_back_every_reservation_when_one_item_is_unavailable(): void
    {
        $this->createTenant('sonder', 'Sonder', 'sonder.com.ar');
        $user = User::factory()->create();
        $availableVariant = $this->createVariantForTenant('sonder', 1, '50.00');
        $unavailableInventory = Inventory::query()->create(['real_stock' => 0]);
        $unavailableVariant = Variant::query()->create([
            'catalog_item_id' => $availableVariant->catalog_item_id,
            'inventory_id' => $unavailableInventory->id,
        ]);

        $this->actingAs($user, 'sanctum')
            ->postJson('/api/tenants/sonder/compras/start-checkout', [
                'direct_items' => [
                    [
                        'catalog_item_id' => $availableVariant->catalog_item_id,
                        'variant_id' => $availableVariant->id,
                        'cantidad' => 1,
                    ],
                    [
                        'catalog_item_id' => $unavailableVariant->catalog_item_id,
                        'variant_id' => $unavailableVariant->id,
                        'cantidad' => 1,
                    ],
                ],
            ])
            ->assertUnprocessable()
            ->assertJsonValidationErrors('direct_items.1.cantidad');

        $this->assertDatabaseCount('compras', 0);
        $this->assertDatabaseHas('inventories', [
            'id' => $availableVariant->inventory_id,
            'reserved_stock' => 0,
        ]);
        $this->assertDatabaseHas('inventories', [
            'id' => $unavailableInventory->id,
            'reserved_stock' => 0,
        ]);
    }

    public function test_it_enforces_the_user_purchase_limit_and_releases_it_after_cancellation(): void
    {
        $this->createTenant('sonder', 'Sonder', 'sonder.com.ar');
        $user = User::factory()->create();
        $otherUser = User::factory()->create();
        $variant = $this->createVariantForTenant('sonder', 20, '50.00');
        $variant->catalogItem->update(['max_units_per_user' => 3]);

        $firstPurchaseId = $this->actingAs($user, 'sanctum')
            ->postJson('/api/tenants/sonder/compras/start-checkout', [
                'direct_items' => [
                    [
                        'catalog_item_id' => $variant->catalog_item_id,
                        'variant_id' => $variant->id,
                        'cantidad' => 2,
                    ],
                ],
            ])
            ->assertCreated()
            ->json('data.id');

        $this->actingAs($user, 'sanctum')
            ->postJson('/api/tenants/sonder/compras/start-checkout', [
                'direct_items' => [
                    [
                        'catalog_item_id' => $variant->catalog_item_id,
                        'variant_id' => $variant->id,
                        'cantidad' => 2,
                    ],
                ],
            ])
            ->assertUnprocessable()
            ->assertJsonValidationErrors('direct_items')
            ->assertJsonPath('code', 'purchase.limit_exceeded')
            ->assertJsonPath('catalog_item_id', $variant->catalog_item_id)
            ->assertJsonPath('catalog_item_name', $variant->catalogItem->nombre)
            ->assertJsonPath('maximum_addable_quantity', 1);

        $this->actingAs($otherUser, 'sanctum')
            ->postJson('/api/tenants/sonder/compras/start-checkout', [
                'direct_items' => [
                    [
                        'catalog_item_id' => $variant->catalog_item_id,
                        'variant_id' => $variant->id,
                        'cantidad' => 3,
                    ],
                ],
            ])
            ->assertCreated();

        $this->actingAs($user, 'sanctum')
            ->postJson("/api/tenants/sonder/compras/{$firstPurchaseId}/cancel")
            ->assertOk();

        $this->actingAs($user, 'sanctum')
            ->postJson('/api/tenants/sonder/compras/start-checkout', [
                'direct_items' => [
                    [
                        'catalog_item_id' => $variant->catalog_item_id,
                        'variant_id' => $variant->id,
                        'cantidad' => 3,
                    ],
                ],
            ])
            ->assertCreated();
    }

    public function test_the_user_purchase_limit_is_shared_by_all_item_variants(): void
    {
        $tenant = $this->createTenant('sonder', 'Sonder', 'sonder.com.ar');
        $user = User::factory()->create();
        $firstVariant = $this->createVariantForTenant('sonder', 20, '50.00');
        $firstVariant->catalogItem->update(['max_units_per_user' => 3]);
        $secondInventory = Inventory::query()->create(['real_stock' => 20]);
        $secondVariant = Variant::query()->create([
            'catalog_item_id' => $firstVariant->catalog_item_id,
            'inventory_id' => $secondInventory->id,
        ]);
        $cart = Cart::query()->create([
            'tenant_codigo' => $tenant->codigo,
            'user_id' => $user->id,
            'status' => 'active',
        ]);
        $cart->addItem($firstVariant->catalog_item_id, $firstVariant->id, 2);
        $cart->addItem($secondVariant->catalog_item_id, $secondVariant->id, 2);

        $this->actingAs($user, 'sanctum')
            ->postJson('/api/tenants/sonder/compras/start-checkout', [
                'cart_id' => $cart->id,
            ])
            ->assertUnprocessable()
            ->assertJsonValidationErrors('cart_id');

        $this->assertDatabaseCount('compras', 0);
        $this->assertDatabaseHas('inventories', [
            'id' => $firstVariant->inventory_id,
            'reserved_stock' => 2,
        ]);
        $this->assertDatabaseHas('inventories', [
            'id' => $secondInventory->id,
            'reserved_stock' => 2,
        ]);
    }

    public function test_it_keeps_the_source_cart_active_and_only_cancels_the_purchase(): void
    {
        $this->createTenant('sonder', 'Sonder', 'sonder.com.ar');
        $user = User::factory()->create();
        $variant = $this->createVariantForTenant('sonder', 10, '50.00');
        $purchase = $this->createCheckoutPurchase($user, 'sonder', $variant, 3);
        $activeCart = Cart::query()
            ->where('user_id', $user->id)
            ->where('status', 'active')
            ->firstOrFail();
        $cartItemId = $purchase->cart->items()->firstOrFail()->id;

        $this->assertDatabaseHas('carritos', [
            'id' => $purchase->cart_id,
            'status' => 'active',
            'origin' => Cart::ORIGIN_USER,
            'current_purchase_id' => $purchase->id,
            'deleted_at' => null,
        ]);
        $this->assertDatabaseCount('carrito_items', 1);
        $this->assertSame(1, $activeCart->items()->count());

        $this->actingAs($user, 'sanctum')
            ->postJson("/api/tenants/sonder/compras/{$purchase->id}/cancel")
            ->assertOk()
            ->assertJsonPath('data.status', Purchase::STATUS_CANCELLED);

        $this->assertDatabaseHas('carritos', [
            'id' => $activeCart->id,
            'user_id' => $user->id,
            'status' => 'active',
            'current_purchase_id' => null,
            'deleted_at' => null,
        ]);
        $this->assertDatabaseHas('inventories', [
            'id' => $variant->inventory_id,
            'reserved_stock' => 3,
        ]);
        $this->assertDatabaseHas('stock_reservations', [
            'cart_item_id' => $cartItemId,
            'purchase_id' => null,
            'quantity' => 3,
            'status' => 'active',
        ]);
        $this->assertSame(1, $activeCart->items()->count());
    }

    public function test_it_reassigns_a_terminal_purchase_reservation_and_rejects_a_late_confirmation(): void
    {
        $this->createTenant('sonder', 'Sonder', 'sonder.com.ar');
        $user = User::factory()->create();
        $variant = $this->createVariantForTenant('sonder', 10, '50.00');
        $previousPurchase = $this->createCheckoutPurchase($user, 'sonder', $variant, 2);
        $cart = $previousPurchase->cart;

        $previousPurchase->update([
            'status' => Purchase::STATUS_PENDING_PAYMENT,
            'payment_method' => 'transfer',
            'expires_at' => now()->addMinutes(30),
        ]);

        $currentPurchase = app(CheckoutService::class)->startCheckout(
            $previousPurchase->tenant,
            $user->id,
            ['cart_id' => $cart->id],
        );

        $this->assertDatabaseHas('compras', [
            'id' => $previousPurchase->id,
            'status' => Purchase::STATUS_SUPERSEDED,
            'expires_at' => null,
        ]);
        $this->assertDatabaseHas('carritos', [
            'id' => $cart->id,
            'current_purchase_id' => $currentPurchase->id,
        ]);
        $this->assertDatabaseHas('stock_reservations', [
            'purchase_id' => $currentPurchase->id,
            'quantity' => 2,
            'status' => 'active',
        ]);

        try {
            app(CheckoutService::class)->confirmPaidPurchase($previousPurchase->fresh());
            $this->fail('A superseded purchase was allowed to commit the current reservation.');
        } catch (ValidationException $exception) {
            $this->assertArrayHasKey('purchase', $exception->errors());
        }

        $this->assertDatabaseHas('inventories', [
            'id' => $variant->inventory_id,
            'reserved_stock' => 2,
            'sold_units' => 0,
        ]);
        $this->assertDatabaseHas('stock_reservations', [
            'purchase_id' => $currentPurchase->id,
            'quantity' => 2,
            'status' => 'active',
        ]);
    }

    public function test_removing_a_checkout_item_supersedes_the_purchase_and_restores_the_user_quota(): void
    {
        $this->createTenant('sonder', 'Sonder', 'sonder.com.ar');
        $user = User::factory()->create();
        $variant = $this->createVariantForTenant('sonder', 10, '50.00');
        $variant->catalogItem->update(['max_units_per_user' => 3]);
        $purchase = $this->createCheckoutPurchase($user, 'sonder', $variant, 2);
        $cart = $purchase->cart;
        $cartItem = $cart->items()->firstOrFail();

        $cart->removeItem($cartItem->id);

        $this->assertDatabaseHas('compras', [
            'id' => $purchase->id,
            'status' => Purchase::STATUS_SUPERSEDED,
        ]);
        $this->assertDatabaseHas('compra_items', [
            'compra_id' => $purchase->id,
            'source_catalog_item_id' => $variant->catalog_item_id,
            'cantidad' => 2,
        ]);
        $this->assertDatabaseHas('carritos', [
            'id' => $cart->id,
            'current_purchase_id' => null,
        ]);
        $this->assertDatabaseHas('stock_reservations', [
            'inventory_id' => $variant->inventory_id,
            'cart_item_id' => null,
            'purchase_id' => null,
            'quantity' => 0,
            'status' => 'released',
        ]);
        $this->assertDatabaseHas('inventories', [
            'id' => $variant->inventory_id,
            'reserved_stock' => 0,
        ]);

        $remaining = app(UserPurchaseLimitService::class)
            ->remainingByCatalogItem(collect([$variant->catalogItem->fresh()]), $user->id)
            ->get($variant->catalog_item_id);

        $this->assertSame(3, $remaining);
    }

    public function test_it_expires_the_purchase_without_mutating_the_active_cart(): void
    {
        $this->createTenant('sonder', 'Sonder', 'sonder.com.ar');
        $user = User::factory()->create();
        $variant = $this->createVariantForTenant('sonder', 10, '50.00');
        $purchase = $this->createCheckoutPurchase($user, 'sonder', $variant, 3);
        $activeCart = Cart::query()
            ->where('user_id', $user->id)
            ->where('status', 'active')
            ->firstOrFail();
        $cartItemId = $purchase->cart->items()->firstOrFail()->id;
        $purchase->update(['expires_at' => now()->subMinute()]);

        $this->artisan('reservations:expire')->assertSuccessful();

        $this->assertDatabaseHas('compras', [
            'id' => $purchase->id,
            'status' => Purchase::STATUS_EXPIRED,
        ]);
        $this->assertDatabaseHas('inventories', [
            'id' => $variant->inventory_id,
            'reserved_stock' => 3,
        ]);
        $this->assertDatabaseHas('carritos', [
            'id' => $activeCart->id,
            'user_id' => $user->id,
            'status' => 'active',
            'current_purchase_id' => null,
            'deleted_at' => null,
        ]);
        $this->assertDatabaseHas('stock_reservations', [
            'cart_item_id' => $cartItemId,
            'purchase_id' => null,
            'quantity' => 3,
            'status' => 'active',
        ]);
        $this->assertSame(1, $activeCart->items()->count());
    }

    public function test_it_keeps_cart_items_during_checkout_and_updates_customer_data(): void
    {
        $this->createTenant('sonder', 'Sonder', 'sonder.com.ar');
        $user = User::factory()->create();
        $variant = $this->createVariantForTenant('sonder', 10, '50.00');

        $purchaseResponse = $this->actingAs($user, 'sanctum')
            ->postJson('/api/tenants/sonder/compras/start-checkout', [
                'direct_items' => [
                    [
                        'catalog_item_id' => $variant->catalog_item_id,
                        'variant_id' => $variant->id,
                        'cantidad' => 2,
                    ],
                ],
            ])
            ->assertCreated()
            ->assertJsonPath('data.items_source', 'purchase')
            ->assertJsonCount(1, 'data.items')
            ->assertJsonPath('data.items.0.quantity', 2)
            ->assertJsonPath('data.dni', null)
            ->assertJsonPath('data.telefono', null);

        $purchaseId = $purchaseResponse->json('data.id');

        $this->actingAs($user, 'sanctum')
            ->patchJson("/api/tenants/sonder/compras/{$purchaseId}/customer-data", [
                'dni' => '987654321',
                'telefono' => '+54 9 341 555-4321',
                'nombre_apellido' => 'Juan Perez',
                'email' => 'juan.perez@example.com',
            ])
            ->assertOk()
            ->assertJsonPath('data.id', $purchaseId)
            ->assertJsonPath('data.dni', '987654321')
            ->assertJsonPath('data.telefono', '+54 9 341 555-4321')
            ->assertJsonPath('data.nombre_apellido', 'Juan Perez')
            ->assertJsonPath('data.email', 'juan.perez@example.com')
            ->assertJsonCount(1, 'data.items');

        $this->assertDatabaseHas('compras', [
            'id' => $purchaseId,
            'dni' => '987654321',
            'telefono' => '+54 9 341 555-4321',
            'nombre_apellido' => 'Juan Perez',
            'email' => 'juan.perez@example.com',
        ]);
    }

    public function test_it_updates_customer_data_for_a_pending_payment_purchase(): void
    {
        $this->createTenant('sonder', 'Sonder', 'sonder.com.ar');
        $user = User::factory()->create();
        $variant = $this->createVariantForTenant('sonder', 10, '50.00');
        $purchase = $this->createCheckoutPurchase($user, 'sonder', $variant, 1);
        $purchase->update(['status' => Purchase::STATUS_PENDING_PAYMENT]);

        $this->actingAs($user, 'sanctum')
            ->patchJson("/api/tenants/sonder/compras/{$purchase->id}/customer-data", [
                'dni' => '987654321',
                'telefono' => '+54 9 341 555-4321',
                'nombre_apellido' => 'Juan Perez',
                'email' => 'juan.perez@example.com',
            ])
            ->assertOk()
            ->assertJsonPath('data.status', Purchase::STATUS_PENDING_PAYMENT)
            ->assertJsonPath('data.dni', '987654321');

        $this->assertDatabaseHas('compras', [
            'id' => $purchase->id,
            'status' => Purchase::STATUS_PENDING_PAYMENT,
            'dni' => '987654321',
        ]);
    }

    public function test_checkout_items_are_immutable_and_editing_routes_are_unavailable(): void
    {
        $this->createTenant('sonder', 'Sonder', 'sonder.com.ar');
        $user = User::factory()->create();
        $variant = $this->createVariantForTenant('sonder', 10, '50.00');
        $purchase = $this->createCheckoutPurchase($user, 'sonder', $variant, 2);
        $cartItemId = $purchase->cart->items->firstOrFail()->id;
        $purchaseItemId = $purchase->items->firstOrFail()->id;

        $this->actingAs($user, 'sanctum')
            ->patchJson("/api/tenants/sonder/checkout-carts/{$purchase->cart_id}/items/{$cartItemId}", [
                'cantidad' => 3,
            ])
            ->assertNotFound();

        $this->patchJson("/api/tenants/sonder/compras/{$purchase->id}/items/{$purchaseItemId}", [
            'quantity' => 3,
        ])->assertNotFound();

        $this->deleteJson("/api/tenants/sonder/compras/{$purchase->id}/items/{$purchaseItemId}")
            ->assertNotFound();

        $this->postJson("/api/tenants/sonder/compras/{$purchase->id}/edit-items")
            ->assertNotFound();

        $this->assertDatabaseHas('compra_items', [
            'id' => $purchaseItemId,
            'cantidad' => 2,
            'precio_unitario' => '50.00',
            'total' => '100.00',
        ]);
        $this->assertDatabaseHas('inventories', [
            'id' => $variant->inventory_id,
            'reserved_stock' => 2,
        ]);
    }

    public function test_start_checkout_rejects_customer_data(): void
    {
        $this->createTenant('sonder', 'Sonder', 'sonder.com.ar');
        $user = User::factory()->create();
        $variant = $this->createVariantForTenant('sonder', 10, '50.00');

        $this->actingAs($user, 'sanctum')
            ->postJson('/api/tenants/sonder/compras/start-checkout', [
                'direct_items' => [
                    [
                        'catalog_item_id' => $variant->catalog_item_id,
                        'variant_id' => $variant->id,
                        'cantidad' => 1,
                    ],
                ],
                'dni' => '987654321',
                'telefono' => '+54 9 341 555-4321',
                'nombre_apellido' => 'Juan Perez',
                'email' => 'juan.perez@example.com',
            ])
            ->assertUnprocessable()
            ->assertJsonValidationErrors([
                'dni',
                'telefono',
                'nombre_apellido',
                'email',
            ]);
    }

    public function test_it_moves_a_created_purchase_to_pending_payment_when_finalized(): void
    {
        $tenant = $this->createTenant('sonder', 'Sonder', 'sonder.com.ar');
        $user = User::factory()->create([
            'email' => 'buyer@example.com',
        ]);
        $variant = $this->createVariantForTenant('sonder', 10, '50.00');

        $cartId = $this->actingAs($user, 'sanctum')
            ->postJson('/api/tenants/sonder/cart/items', [
                'catalog_item_id' => $variant->catalog_item_id,
                'variant_id' => $variant->id,
                'cantidad' => 2,
            ])
            ->assertOk()
            ->json('data.id');

        $purchaseId = $this->actingAs($user, 'sanctum')
            ->postJson('/api/tenants/sonder/compras/start-checkout', [
                'cart_id' => $cartId,
            ])
            ->assertCreated()
            ->json('data.id');

        Purchase::query()
            ->whereKey($purchaseId)
            ->update([
                'payment_method' => 'transfer',
            ]);

        $this->actingAs($user, 'sanctum')
            ->postJson("/api/tenants/sonder/compras/{$purchaseId}/complete")
            ->assertOk()
            ->assertJsonPath('data.status', Purchase::STATUS_PENDING_PAYMENT);

        $this->assertDatabaseHas('compras', [
            'id' => $purchaseId,
            'status' => Purchase::STATUS_PENDING_PAYMENT,
            'payment_method' => 'transfer',
        ]);
        $this->assertDatabaseHas('value_changes', [
            'trackable_type' => (new Purchase)->getMorphClass(),
            'trackable_id' => $purchaseId,
            'attribute' => 'status',
            'old_value' => Purchase::STATUS_CREATED,
            'new_value' => Purchase::STATUS_PENDING_PAYMENT,
            'actor_type' => 'user',
            'user_id' => $user->id,
        ]);
    }

    public function test_it_moves_a_submitted_purchase_to_review_idempotently(): void
    {
        $this->createTenant('sonder', 'Sonder', 'sonder.com.ar');
        $user = User::factory()->create();
        $variant = $this->createVariantForTenant('sonder', 10, '50.00');
        $purchase = $this->createCheckoutPurchase($user, 'sonder', $variant, 2);

        $purchase->update([
            'payment_method' => 'transfer',
            'status' => Purchase::STATUS_PENDING_PAYMENT,
            'expires_at' => now()->addMinutes(30),
        ]);

        $url = "/api/tenants/sonder/compras/{$purchase->id}/review";

        $this->actingAs($user, 'sanctum')
            ->postJson($url)
            ->assertOk()
            ->assertJsonPath('data.status', Purchase::STATUS_IN_REVIEW)
            ->assertJsonPath('data.expires_at', null);

        $this->assertDatabaseHas('compras', [
            'id' => $purchase->id,
            'status' => Purchase::STATUS_IN_REVIEW,
            'expires_at' => null,
        ]);

        $this->actingAs($user, 'sanctum')
            ->postJson($url)
            ->assertOk()
            ->assertJsonPath('data.status', Purchase::STATUS_IN_REVIEW);

        $this->actingAs($user, 'sanctum')
            ->postJson("/api/tenants/sonder/compras/{$purchase->id}/complete")
            ->assertOk()
            ->assertJsonPath('data.status', Purchase::STATUS_IN_REVIEW);

        $this->actingAs($user, 'sanctum')
            ->postJson("/api/tenants/sonder/compras/{$purchase->id}/payment-intent", [
                'method' => 'qr',
            ])
            ->assertUnprocessable()
            ->assertJsonValidationErrors('purchase');

        $this->assertDatabaseHas('compras', [
            'id' => $purchase->id,
            'status' => Purchase::STATUS_IN_REVIEW,
            'payment_method' => 'transfer',
        ]);

        $sourceCartId = $purchase->cart_id;

        $this->actingAs($user, 'sanctum')
            ->postJson("/api/tenants/sonder/compras/{$purchase->id}/cancel")
            ->assertOk()
            ->assertJsonPath('data.status', Purchase::STATUS_IN_REVIEW);

        $this->assertDatabaseHas('compras', [
            'id' => $purchase->id,
            'status' => Purchase::STATUS_IN_REVIEW,
        ]);
        $this->assertDatabaseHas('carritos', [
            'id' => $sourceCartId,
            'status' => 'checkout',
            'current_purchase_id' => $purchase->id,
            'deleted_at' => null,
        ]);
        $this->assertDatabaseHas('carritos', [
            'tenant_codigo' => 'sonder',
            'user_id' => $user->id,
            'status' => 'active',
            'current_purchase_id' => null,
            'deleted_at' => null,
        ]);
        $this->assertDatabaseHas('stock_reservations', [
            'purchase_id' => $purchase->id,
            'status' => 'active',
        ]);
    }

    public function test_it_rejects_review_for_a_purchase_that_is_not_awaiting_payment(): void
    {
        $this->createTenant('sonder', 'Sonder', 'sonder.com.ar');
        $user = User::factory()->create();
        $variant = $this->createVariantForTenant('sonder', 10, '50.00');
        $purchase = $this->createCheckoutPurchase($user, 'sonder', $variant, 1);

        $this->actingAs($user, 'sanctum')
            ->postJson("/api/tenants/sonder/compras/{$purchase->id}/review")
            ->assertUnprocessable()
            ->assertJsonValidationErrors(['purchase']);

        $this->assertDatabaseHas('compras', [
            'id' => $purchase->id,
            'status' => Purchase::STATUS_CREATED,
        ]);
    }

    public function test_it_expires_an_abandoned_purchase_without_mutating_its_active_cart(): void
    {
        $this->createTenant('sonder', 'Sonder', 'sonder.com.ar');
        $user = User::factory()->create();
        $variant = $this->createVariantForTenant('sonder', 10, '50.00');
        $purchase = $this->createCheckoutPurchase($user, 'sonder', $variant, 3);
        $activeCart = Cart::query()
            ->where('user_id', $user->id)
            ->where('status', 'active')
            ->firstOrFail();

        $this->assertNotNull($purchase->expires_at);
        $this->assertDatabaseHas('inventories', [
            'id' => $variant->inventory_id,
            'reserved_stock' => 3,
        ]);

        $this->travel(31)->minutes();

        $this->artisan('reservations:expire')
            ->expectsOutput('Expired purchases: 1')
            ->expectsOutput('Expired cart items: 0')
            ->assertSuccessful();

        $this->assertDatabaseHas('compras', [
            'id' => $purchase->id,
            'status' => Purchase::STATUS_EXPIRED,
        ]);
        $this->assertDatabaseHas('compra_items', [
            'compra_id' => $purchase->id,
            'cantidad' => 3,
        ]);
        $this->assertDatabaseHas('stock_reservations', [
            'purchase_id' => null,
            'quantity' => 3,
            'status' => 'active',
        ]);
        $this->assertDatabaseHas('inventories', [
            'id' => $variant->inventory_id,
            'real_stock' => 10,
            'reserved_stock' => 3,
            'sold_units' => 0,
        ]);
        $this->assertDatabaseHas('carritos', [
            'id' => $activeCart->id,
            'user_id' => $user->id,
            'status' => 'active',
            'deleted_at' => null,
        ]);
        $this->assertSame(1, $activeCart->items()->count());

        $this->artisan('reservations:expire')
            ->expectsOutput('Expired purchases: 0')
            ->expectsOutput('Expired cart items: 0')
            ->assertSuccessful();
    }

    public function test_it_expires_multiple_purchases_that_already_have_item_snapshots(): void
    {
        $this->createTenant('sonder', 'Sonder', 'sonder.com.ar');
        $user = User::factory()->create();
        $secondUser = User::factory()->create();
        $variant = $this->createVariantForTenant('sonder', 10, '50.00');
        $inconsistentPurchase = $this->createCheckoutPurchase($user, 'sonder', $variant, 1);
        $validPurchase = $this->createCheckoutPurchase($secondUser, 'sonder', $variant, 1);

        $inconsistentPurchase->items()->create([
            'source_catalog_item_id' => $variant->catalog_item_id,
            'source_variant_id' => $variant->id,
            'nombre' => 'Inconsistent item',
            'slug' => 'inconsistent-item',
            'cantidad' => 1,
            'precio_unitario' => '50.00',
            'discount_total' => '0.00',
            'tax_total' => '0.00',
            'total' => '50.00',
        ]);

        $this->travel(31)->minutes();

        $this->artisan('reservations:expire')
            ->expectsOutput('Expired purchases: 2')
            ->expectsOutput('Expired cart items: 0')
            ->assertSuccessful();

        $this->assertDatabaseHas('compras', [
            'id' => $inconsistentPurchase->id,
            'status' => Purchase::STATUS_EXPIRED,
        ]);
        $this->assertDatabaseHas('compras', [
            'id' => $validPurchase->id,
            'status' => Purchase::STATUS_EXPIRED,
        ]);
    }

    public function test_purchase_detail_uses_purchase_item_snapshot_for_created_purchase(): void
    {
        $this->createTenant('sonder', 'Sonder', 'sonder.com.ar');
        $user = User::factory()->create([
            'email' => 'buyer@example.com',
        ]);
        $variant = $this->createVariantForTenant('sonder', 10, '50.00');
        $purchase = $this->createCheckoutPurchase($user, 'sonder', $variant, 2);

        $this->actingAs($user, 'sanctum')
            ->getJson("/api/tenants/sonder/compras/{$purchase->id}")
            ->assertOk()
            ->assertJsonPath('data.status', Purchase::STATUS_CREATED)
            ->assertJsonPath('data.items_source', 'purchase')
            ->assertJsonCount(1, 'data.items')
            ->assertJsonPath('data.items.0.quantity', 2)
            ->assertJsonPath('data.items.0.unit_price', '50.00')
            ->assertJsonPath('data.items.0.line_total', '100.00')
            ->assertJsonPath('data.items.0.source_catalog_item_id', $variant->catalogItem->id)
            ->assertJsonPath('data.items.0.source_variant_id', $variant->id)
            ->assertJsonPath('data.items.0.item_details.nombre', $variant->catalogItem->nombre)
            ->assertJsonPath('data.items.0.item_details.slug', $variant->catalogItem->slug)
            ->assertJsonPath('data.items.0.item_details.imagen', null)
            ->assertJsonPath('data.items.0.item_details.attributes', [])
            ->assertJsonPath('data.subtotal', '100.00')
            ->assertJsonPath('data.total', '100.00');
    }

    public function test_purchase_detail_filters_item_images_when_the_tenant_disables_them(): void
    {
        $tenant = $this->createTenant('sonder', 'Sonder', 'sonder.com.ar');
        $tenant->update(['display_cart_item_images' => false]);
        $user = User::factory()->create([
            'email' => 'buyer@example.com',
        ]);
        $variant = $this->createVariantForTenant('sonder', 10, '50.00');
        $purchase = $this->createCheckoutPurchase($user, 'sonder', $variant, 2);
        $image = Attachment::create([
            'key' => (string) Str::uuid(),
            'path' => 'catalog/purchase-item.png',
            'filename' => 'purchase-item.png',
            'type' => AttachmentType::Image,
            'mime_type' => 'image/png',
        ]);
        $variant->catalogItem->attachments()->attach($image->id, ['orden' => 0]);

        $this->actingAs($user, 'sanctum')
            ->getJson("/api/tenants/sonder/compras/{$purchase->id}")
            ->assertOk()
            ->assertJsonPath('data.items.0.item_details.imagen', null);
    }

    public function test_purchase_detail_uses_purchase_item_snapshot_for_pending_payment_purchase(): void
    {
        $this->createTenant('sonder', 'Sonder', 'sonder.com.ar');
        $user = User::factory()->create([
            'email' => 'buyer@example.com',
        ]);
        $variant = $this->createVariantForTenant('sonder', 10, '50.00');
        $purchase = $this->createCheckoutPurchase($user, 'sonder', $variant, 2);

        $purchase->update([
            'payment_method' => 'transfer',
        ]);

        app(CheckoutService::class)->completePurchase($purchase);

        $this->actingAs($user, 'sanctum')
            ->getJson("/api/tenants/sonder/compras/{$purchase->id}")
            ->assertOk()
            ->assertJsonPath('data.status', Purchase::STATUS_PENDING_PAYMENT)
            ->assertJsonPath('data.items_source', 'purchase')
            ->assertJsonCount(1, 'data.items')
            ->assertJsonPath('data.items.0.quantity', 2)
            ->assertJsonPath('data.items.0.unit_price', '50.00')
            ->assertJsonPath('data.items.0.line_total', '100.00')
            ->assertJsonPath('data.items.0.item_details.imagen', null)
            ->assertJsonPath('data.items.0.item_details.attributes', [])
            ->assertJsonPath('data.subtotal', '100.00')
            ->assertJsonPath('data.total', '100.00');
    }

    public function test_created_and_pending_payment_purchase_details_ignore_later_cart_changes(): void
    {
        $this->createTenant('sonder', 'Sonder', 'sonder.com.ar');
        $variant = $this->createVariantForTenant('sonder', 10, '50.00');

        foreach ([Purchase::STATUS_CREATED, Purchase::STATUS_PENDING_PAYMENT] as $status) {
            $user = User::factory()->create();
            $purchase = $this->createCheckoutPurchase($user, 'sonder', $variant, 2);
            $purchase->cart->items()->update(['cantidad' => 3]);
            $purchase->update(['status' => $status]);

            $this->actingAs($user, 'sanctum')
                ->getJson("/api/tenants/sonder/compras/{$purchase->id}")
                ->assertOk()
                ->assertJsonPath('data.status', $status)
                ->assertJsonPath('data.items_source', 'purchase')
                ->assertJsonPath('data.items.0.quantity', 2)
                ->assertJsonPath('data.items.0.line_total', '100.00')
                ->assertJsonPath('data.subtotal', '100.00')
                ->assertJsonPath('data.total', '100.00');
        }
    }

    public function test_purchase_detail_uses_purchase_items_for_paid_purchase_even_without_cart(): void
    {
        $this->createTenant('sonder', 'Sonder', 'sonder.com.ar');
        $user = User::factory()->create([
            'email' => 'buyer@example.com',
        ]);
        $variant = $this->createVariantForTenant('sonder', 10, '50.00');
        $purchase = $this->createCheckoutPurchase($user, 'sonder', $variant, 2);

        $purchase->update([
            'payment_method' => 'transfer',
        ]);

        $checkoutService = app(CheckoutService::class);
        $purchase = $checkoutService->completePurchase($purchase);
        $checkoutService->confirmPurchase($purchase);
        $purchase->refresh()->markAsPaid();

        $this->assertDatabaseHas('inventories', [
            'id' => $variant->inventory_id,
            'real_stock' => 8,
            'reserved_stock' => 0,
            'sold_units' => 2,
        ]);
        $this->assertDatabaseHas('stock_reservations', [
            'purchase_id' => $purchase->id,
            'inventory_id' => $variant->inventory_id,
            'quantity' => 2,
            'status' => 'committed',
        ]);

        $this->assertSoftDeleted('carritos', [
            'id' => $purchase->cart_id,
        ]);

        $this->actingAs($user, 'sanctum')
            ->getJson("/api/tenants/sonder/compras/{$purchase->id}")
            ->assertOk()
            ->assertJsonPath('data.status', Purchase::STATUS_PAID)
            ->assertJsonPath('data.items_source', 'purchase')
            ->assertJsonCount(1, 'data.items')
            ->assertJsonPath('data.items.0.quantity', 2)
            ->assertJsonPath('data.items.0.unit_price', '50.00')
            ->assertJsonPath('data.items.0.line_total', '100.00')
            ->assertJsonPath('data.items.0.source_catalog_item_id', $variant->catalog_item_id)
            ->assertJsonPath('data.items.0.source_variant_id', $variant->id)
            ->assertJsonPath('data.items.0.item_details.imagen', null)
            ->assertJsonPath('data.items.0.item_details.attributes', [])
            ->assertJsonPath('data.subtotal', '100.00')
            ->assertJsonPath('data.total', '100.00');
    }

    public function test_purchase_detail_does_not_require_its_source_cart(): void
    {
        $this->createTenant('sonder', 'Sonder', 'sonder.com.ar');
        $user = User::factory()->create([
            'email' => 'buyer@example.com',
        ]);
        $variant = $this->createVariantForTenant('sonder', 10, '50.00');
        $purchase = $this->createCheckoutPurchase($user, 'sonder', $variant, 2);

        $purchase->update(['payment_method' => 'transfer']);
        app(CheckoutService::class)->confirmPurchase($purchase);
        $purchase->refresh()->update(['cart_id' => null]);

        $this->actingAs($user, 'sanctum')
            ->getJson("/api/tenants/sonder/compras/{$purchase->id}")
            ->assertOk()
            ->assertJsonPath('data.items_source', 'purchase')
            ->assertJsonCount(1, 'data.items')
            ->assertJsonPath('data.items.0.quantity', 2)
            ->assertJsonPath('data.items.0.line_total', '100.00')
            ->assertJsonPath('data.subtotal', '100.00')
            ->assertJsonPath('data.total', '100.00');
    }

    public function test_purchase_index_returns_empty_items_without_loaded_relations(): void
    {
        $this->createTenant('sonder', 'Sonder', 'sonder.com.ar');
        $user = User::factory()->create([
            'email' => 'buyer@example.com',
        ]);
        $variant = $this->createVariantForTenant('sonder', 10, '50.00');
        $this->createCheckoutPurchase($user, 'sonder', $variant, 2);

        $this->actingAs($user, 'sanctum')
            ->getJson('/api/tenants/sonder/compras?status=created')
            ->assertOk()
            ->assertJsonCount(1, 'data')
            ->assertJsonPath('data.0.items_source', null)
            ->assertJsonPath('data.0.items', [])
            ->assertJsonPath('data.0.total', '100.00');
    }

    public function test_purchase_index_filters_multiple_comma_separated_statuses_and_orders_by_status_ascending_then_date(): void
    {
        $this->createTenant('sonder', 'Sonder', 'sonder.com.ar');
        $user = User::factory()->create();

        $olderPaid = Purchase::query()->create([
            'tenant_codigo' => 'sonder',
            'user_id' => $user->id,
            'status' => Purchase::STATUS_PAID,
            'total' => '10.00',
        ]);
        $newerInReview = Purchase::query()->create([
            'tenant_codigo' => 'sonder',
            'user_id' => $user->id,
            'status' => Purchase::STATUS_IN_REVIEW,
            'total' => '20.00',
        ]);
        $newerPaid = Purchase::query()->create([
            'tenant_codigo' => 'sonder',
            'user_id' => $user->id,
            'status' => Purchase::STATUS_PAID,
            'total' => '30.00',
        ]);
        Purchase::query()->create([
            'tenant_codigo' => 'sonder',
            'user_id' => $user->id,
            'status' => Purchase::STATUS_CANCELLED,
            'total' => '40.00',
        ]);

        $olderPaid->forceFill(['created_at' => now()->subDays(3)])->saveQuietly();
        $newerInReview->forceFill(['created_at' => now()])->saveQuietly();
        $newerPaid->forceFill(['created_at' => now()->subDay()])->saveQuietly();

        $this->actingAs($user, 'sanctum')
            ->getJson('/api/tenants/sonder/compras?status=paid,%20in_review,paid')
            ->assertOk()
            ->assertJsonCount(3, 'data')
            ->assertJsonPath('data.0.id', $newerInReview->id)
            ->assertJsonPath('data.0.status', Purchase::STATUS_IN_REVIEW)
            ->assertJsonPath('data.1.id', $newerPaid->id)
            ->assertJsonPath('data.1.status', Purchase::STATUS_PAID)
            ->assertJsonPath('data.2.id', $olderPaid->id)
            ->assertJsonPath('data.2.status', Purchase::STATUS_PAID);
    }

    public function test_it_rejects_a_cart_from_another_user(): void
    {
        $this->createTenant('sonder', 'Sonder', 'sonder.com.ar');
        $owner = User::factory()->create();
        $attacker = User::factory()->create();
        $variant = $this->createVariantForTenant('sonder', 10, '50.00');

        $cartId = $this->actingAs($owner, 'sanctum')
            ->postJson('/api/tenants/sonder/cart/items', [
                'catalog_item_id' => $variant->catalog_item_id,
                'variant_id' => $variant->id,
                'cantidad' => 1,
            ])
            ->assertOk()
            ->json('data.id');

        $this->actingAs($attacker, 'sanctum')
            ->postJson('/api/tenants/sonder/compras/start-checkout', [
                'cart_id' => $cartId,
            ])
            ->assertNotFound();
    }

    public function test_it_rejects_a_cart_from_another_tenant(): void
    {
        $this->createTenant('sonder', 'Sonder', 'sonder.com.ar');
        $this->createTenant('globex', 'Globex', 'globex.com.ar');
        $user = User::factory()->create();
        $variant = $this->createVariantForTenant('globex', 10, '50.00');

        $cartId = $this->actingAs($user, 'sanctum')
            ->postJson('/api/tenants/globex/cart/items', [
                'catalog_item_id' => $variant->catalog_item_id,
                'variant_id' => $variant->id,
                'cantidad' => 1,
            ])
            ->assertOk()
            ->json('data.id');

        $this->actingAs($user, 'sanctum')
            ->postJson('/api/tenants/sonder/compras/start-checkout', [
                'cart_id' => $cartId,
            ])
            ->assertNotFound();
    }

    public function test_it_rejects_an_empty_cart(): void
    {
        $this->createTenant('sonder', 'Sonder', 'sonder.com.ar');
        $user = User::factory()->create();
        $cart = Cart::query()->create([
            'tenant_codigo' => 'sonder',
            'user_id' => $user->id,
            'status' => 'active',
        ]);

        $this->actingAs($user, 'sanctum')
            ->postJson('/api/tenants/sonder/compras/start-checkout', [
                'cart_id' => $cart->id,
            ])
            ->assertUnprocessable()
            ->assertJsonValidationErrors(['cart_id']);
    }

    public function test_it_rejects_a_converted_cart(): void
    {
        $this->createTenant('sonder', 'Sonder', 'sonder.com.ar');
        $user = User::factory()->create();
        $cart = Cart::query()->create([
            'tenant_codigo' => 'sonder',
            'user_id' => $user->id,
            'status' => 'converted',
        ]);

        $this->actingAs($user, 'sanctum')
            ->postJson('/api/tenants/sonder/compras/start-checkout', [
                'cart_id' => $cart->id,
            ])
            ->assertUnprocessable()
            ->assertJsonValidationErrors(['cart_id']);
    }

    public function test_it_confirms_unlimited_inventory_without_reducing_real_stock_and_is_idempotent(): void
    {
        $this->createTenant('sonder', 'Sonder', 'sonder.com.ar');
        $user = User::factory()->create();
        $variant = $this->createVariantForTenant(
            'sonder',
            0,
            '50.00',
            'unlimited',
            InventoryPolicy::Unlimited,
        );
        $purchase = $this->createCheckoutPurchase($user, 'sonder', $variant, 25);
        $purchase->update(['payment_method' => 'transfer']);

        $checkoutService = app(CheckoutService::class);
        $purchase = $checkoutService->completePurchase($purchase);
        $checkoutService->confirmPurchase($purchase);
        $checkoutService->confirmPurchase($purchase);

        $this->assertDatabaseHas('inventories', [
            'id' => $variant->inventory_id,
            'real_stock' => 0,
            'reserved_stock' => 0,
            'sold_units' => 25,
        ]);
        $this->assertDatabaseCount('compra_items', 1);
    }

    protected function createVariantForTenant(
        string $tenantCode,
        int $stock,
        string $price,
        string $slugPrefix = 'shirt',
        InventoryPolicy $inventoryPolicy = InventoryPolicy::Tracked,
    ): Variant {
        $tenant = Tenant::query()->where('codigo', $tenantCode)->first();
        if (! $tenant) {
            $this->createTenant($tenantCode, ucfirst($tenantCode), "{$tenantCode}.com");
        }

        $category = Category::query()->create([
            'tenant_code' => $tenantCode,
            'nombre' => "{$slugPrefix} category {$tenantCode}",
        ]);

        $inventory = Inventory::query()->create(['real_stock' => $stock]);
        $catalogItem = CatalogItem::query()->create([
            'tenant_code' => $tenantCode,
            'category_id' => $category->id,
            'slug' => "{$slugPrefix}-{$tenantCode}-".CatalogItem::query()->count(),
            'nombre' => ucfirst($slugPrefix)." {$tenantCode}",
            'descripcion' => 'Test product',
            'precio' => $price,
            'inventory_policy' => $inventoryPolicy,
        ]);

        return Variant::query()->create([
            'catalog_item_id' => $catalogItem->id,
            'inventory_id' => $inventory->id,
        ])->load(['catalogItem', 'inventory']);
    }

    protected function createCheckoutPurchase(
        User $user,
        string $tenantCode,
        Variant $variant,
        int $quantity,
    ): Purchase {
        $tenant = Tenant::query()->where('codigo', $tenantCode)->firstOrFail();
        $cart = Cart::query()->create([
            'tenant_codigo' => $tenantCode,
            'user_id' => $user->id,
            'status' => 'active',
        ]);

        $cart->addItem($variant->catalog_item_id, $variant->id, $quantity);

        return app(CheckoutService::class)->startCheckout($tenant, $user->id, [
            'cart_id' => $cart->id,
        ]);
    }

    protected function createTenant(string $codigo, string $nombre, string $dominio): Tenant
    {
        $hdrKey = (string) Str::uuid();
        $ftrKey = (string) Str::uuid();

        $headerAttachment = Attachment::create([
            'key' => $hdrKey,
            'path' => 'tenants/'.$hdrKey.'.png',
            'filename' => 'logo_header.png',
            'type' => AttachmentType::Image,
            'mime_type' => 'image/png',
        ]);
        $footerAttachment = Attachment::create([
            'key' => $ftrKey,
            'path' => 'tenants/'.$ftrKey.'.png',
            'filename' => 'logo_footer.png',
            'type' => AttachmentType::Image,
            'mime_type' => 'image/png',
        ]);

        return Tenant::create([
            'codigo' => $codigo,
            'nombre' => $nombre,
            'dominio' => $dominio,
            'primary_color' => '#111111',
            'secondary_color' => '#222222',
            'danger_color' => '#333333',
            'success_color' => '#28a745',
            'header_bg_color' => '#444444',
            'footer_bg_color' => '#444444',
            'header_logo_id' => $headerAttachment->id,
            'footer_logo_id' => $footerAttachment->id,
        ]);
    }
}
