<?php

namespace Tests\Feature\Cart;

use App\Domains\Attachable\Enums\AttachmentType;
use App\Domains\Attachable\Models\Attachment;
use App\Domains\Auth\Models\User;
use App\Domains\Catalog\Enums\InventoryPolicy;
use App\Domains\Catalog\Models\CatalogItem;
use App\Domains\Catalog\Models\Inventory;
use App\Domains\Catalog\Models\Variant;
use App\Domains\Purchase\Models\Purchase;
use App\Domains\Purchase\Models\PurchaseItem;
use App\Domains\Tenant\Models\Tenant;
use Illuminate\Foundation\Testing\RefreshDatabase;
use Illuminate\Support\Facades\Schema;
use Tests\TestCase;

class CartControllerTest extends TestCase
{
    use RefreshDatabase;

    public function test_cart_items_have_explicit_catalog_and_optional_variant_keys(): void
    {
        $this->assertTrue(Schema::hasColumns('carrito_items', [
            'catalog_item_id',
            'variant_id',
        ]));
        $this->assertFalse(Schema::hasColumn('carrito_items', 'buyable_type'));
        $this->assertFalse(Schema::hasColumn('carrito_items', 'buyable_id'));
    }

    public function test_it_adds_a_catalog_item_without_a_variant(): void
    {
        config()->set('session.domain', '.qa.shopit.com.ar');
        config()->set('session.secure', true);
        config()->set('session.same_site', 'none');

        $tenant = $this->createTenant('acme');
        $item = $this->createDirectItem($tenant, 10, '49.90');

        $response = $this->postJson('/api/tenants/acme/cart/items', [
            'catalog_item_id' => $item->id,
            'cantidad' => 2,
        ]);

        $response
            ->assertOk()
            ->assertCookie('guest_token')
            ->assertJsonPath('data.items.0.catalog_item_id', $item->id)
            ->assertJsonPath('data.items.0.variant_id', null)
            ->assertJsonPath('data.items.0.variant', null)
            ->assertJsonPath('data.items.0.cantidad', 2)
            ->assertJsonPath('data.items.0.precio_unitario', '49.90')
            ->assertJsonPath('data.items.0.nombre', 'Item acme')
            ->assertJsonPath('data.items.0.imagen', null)
            ->assertJsonMissingPath('data.items.0.product')
            ->assertJsonPath('data.subtotal', '99.80');

        $guestTokenCookie = $response->getCookie('guest_token', false);
        $this->assertNotNull($guestTokenCookie);
        $this->assertSame('.qa.shopit.com.ar', $guestTokenCookie->getDomain());
        $this->assertTrue($guestTokenCookie->isSecure());
        $this->assertTrue($guestTokenCookie->isHttpOnly());
        $this->assertSame('none', $guestTokenCookie->getSameSite());
        $this->assertTrue($guestTokenCookie->isPartitioned());

        $this->assertDatabaseHas('carrito_items', [
            'catalog_item_id' => $item->id,
            'variant_id' => null,
            'cantidad' => 2,
        ]);
        $this->assertDatabaseHas('inventories', [
            'id' => $item->inventory_id,
            'reserved_stock' => 2,
        ]);
        $this->assertDatabaseHas('stock_reservations', [
            'inventory_id' => $item->inventory_id,
            'quantity' => 2,
            'status' => 'active',
        ]);
    }

    public function test_it_sets_the_configured_expiration_when_creating_a_stock_reservation(): void
    {
        config()->set('catalog.stock_reservation_expiration_minutes', 45);
        $now = now()->startOfSecond();
        $this->travelTo($now);

        $tenant = $this->createTenant('acme');
        $item = $this->createDirectItem($tenant, 10, '49.90');

        $this->postJson('/api/tenants/acme/cart/items', [
            'catalog_item_id' => $item->id,
            'cantidad' => 2,
        ])->assertOk();

        $this->assertDatabaseHas('stock_reservations', [
            'inventory_id' => $item->inventory_id,
            'quantity' => 2,
            'status' => 'active',
            'expires_at' => $now->copy()->addMinutes(45)->toDateTimeString(),
        ]);

        $this->travelBack();
    }

    public function test_it_expires_abandoned_cart_reservations_and_removes_empty_carts(): void
    {
        config()->set('catalog.stock_reservation_expiration_minutes', 30);
        $tenant = $this->createTenant('acme');
        $item = $this->createDirectItem($tenant, 10, '49.90');

        $response = $this->postJson('/api/tenants/acme/cart/items', [
            'catalog_item_id' => $item->id,
            'cantidad' => 2,
        ])->assertOk();
        $cartId = $response->json('data.id');
        $cartItemId = $response->json('data.items.0.id');

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

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

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

        $this->assertDatabaseHas('inventories', [
            'id' => $item->inventory_id,
            'real_stock' => 10,
            'reserved_stock' => 0,
        ]);
        $this->assertDatabaseMissing('carrito_items', ['id' => $cartItemId]);
        $this->assertSoftDeleted('carritos', [
            'id' => $cartId,
            'status' => 'expired',
        ]);
        $this->assertDatabaseHas('stock_reservations', [
            'inventory_id' => $item->inventory_id,
            'cart_item_id' => null,
            'purchase_id' => null,
            'quantity' => 0,
            'status' => 'expired',
            'expires_at' => null,
        ]);

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

        $this->travelBack();
    }

    public function test_it_filters_item_images_when_the_tenant_disables_them(): void
    {
        $tenant = $this->createTenant('acme');
        $tenant->update(['display_cart_item_images' => false]);
        $item = $this->createDirectItem($tenant, 10, '49.90');
        $item->attachments()->attach($this->createAttachment('cart-item'), ['orden' => 0]);

        $this->postJson('/api/tenants/acme/cart/items', [
            'catalog_item_id' => $item->id,
            'cantidad' => 1,
        ])
            ->assertOk()
            ->assertJsonPath('data.items.0.imagen', null);
    }

    public function test_it_adds_a_specific_variant_and_merges_repeated_additions(): void
    {
        $tenant = $this->createTenant('acme');
        [$item, $variant] = $this->createVariantItem($tenant, 12, '25.00');

        $firstResponse = $this->postJson('/api/tenants/acme/cart/items', [
            'catalog_item_id' => $item->id,
            'variant_id' => $variant->id,
            'cantidad' => 2,
        ])->assertOk();

        $guestToken = $firstResponse->getCookie('guest_token', false)?->getValue();

        $response = $this->call(
            'POST',
            '/api/tenants/acme/cart/items',
            [],
            ['guest_token' => $guestToken],
            [],
            ['HTTP_Accept' => 'application/json', 'CONTENT_TYPE' => 'application/json'],
            json_encode([
                'catalog_item_id' => $item->id,
                'variant_id' => $variant->id,
                'cantidad' => 3,
            ]),
        );

        $response
            ->assertOk()
            ->assertJsonPath('data.items.0.catalog_item_id', $item->id)
            ->assertJsonPath('data.items.0.variant_id', $variant->id)
            ->assertJsonPath('data.items.0.variants.0.id', $variant->id)
            ->assertJsonPath('data.items.0.cantidad', 5)
            ->assertJsonPath('data.subtotal', '125.00');

        $this->assertDatabaseCount('carrito_items', 1);
        $this->assertDatabaseHas('inventories', [
            'id' => $variant->inventory_id,
            'reserved_stock' => 5,
        ]);
        $this->assertDatabaseHas('stock_reservations', [
            'cart_item_id' => $response->json('data.items.0.id'),
            'inventory_id' => $variant->inventory_id,
            'quantity' => 5,
            'status' => 'active',
        ]);
    }

    public function test_authenticated_cart_respects_previous_purchases_and_repeated_additions(): void
    {
        $tenant = $this->createTenant('acme');
        $user = User::factory()->create();
        $item = $this->createDirectItem($tenant, 20, '10.00');
        $item->update(['max_units_per_user' => 4]);
        $this->createPurchaseItem($tenant, $user, $item, 1);

        $this->actingAs($user, 'sanctum')
            ->postJson('/api/tenants/acme/cart/items', [
                'catalog_item_id' => $item->id,
                'cantidad' => 2,
            ])
            ->assertOk()
            ->assertJsonPath('data.items.0.cantidad', 2);

        $this->actingAs($user, 'sanctum')
            ->postJson('/api/tenants/acme/cart/items', [
                'catalog_item_id' => $item->id,
                'cantidad' => 2,
            ])
            ->assertUnprocessable()
            ->assertJsonValidationErrors('cantidad')
            ->assertJsonPath('code', 'purchase.limit_exceeded')
            ->assertJsonPath('catalog_item_id', $item->id)
            ->assertJsonPath('catalog_item_name', $item->nombre)
            ->assertJsonPath('maximum_addable_quantity', 1)
            ->assertJsonPath(
                'message',
                "Podés agregar hasta 1 unidad más de “{$item->nombre}”.",
            );

        $this->assertDatabaseHas('carrito_items', [
            'catalog_item_id' => $item->id,
            'cantidad' => 2,
        ]);
        $this->assertDatabaseHas('inventories', [
            'id' => $item->inventory_id,
            'reserved_stock' => 2,
        ]);
    }

    public function test_authenticated_cart_shares_the_purchase_limit_between_variants(): void
    {
        $tenant = $this->createTenant('acme');
        $user = User::factory()->create();
        [$item, $firstVariant] = $this->createVariantItem($tenant, 20, '10.00');
        $item->update(['max_units_per_user' => 3]);
        $secondInventory = Inventory::query()->create(['real_stock' => 20]);
        $secondVariant = $item->variants()->create(['inventory_id' => $secondInventory->id]);

        $this->actingAs($user, 'sanctum')
            ->postJson('/api/tenants/acme/cart/items', [
                'catalog_item_id' => $item->id,
                'variant_id' => $firstVariant->id,
                'cantidad' => 2,
            ])
            ->assertOk();

        $this->actingAs($user, 'sanctum')
            ->postJson('/api/tenants/acme/cart/items', [
                'catalog_item_id' => $item->id,
                'variant_id' => $secondVariant->id,
                'cantidad' => 2,
            ])
            ->assertUnprocessable()
            ->assertJsonValidationErrors('cantidad');

        $this->assertDatabaseCount('carrito_items', 1);
        $this->assertDatabaseHas('inventories', [
            'id' => $secondInventory->id,
            'reserved_stock' => 0,
        ]);
    }

    public function test_authenticated_cart_rejects_quantity_updates_above_the_purchase_limit(): void
    {
        $tenant = $this->createTenant('acme');
        $user = User::factory()->create();
        $item = $this->createDirectItem($tenant, 20, '10.00');
        $item->update(['max_units_per_user' => 3]);

        $response = $this->actingAs($user, 'sanctum')
            ->postJson('/api/tenants/acme/cart/items', [
                'catalog_item_id' => $item->id,
                'cantidad' => 2,
            ])
            ->assertOk();

        $this->actingAs($user, 'sanctum')
            ->patchJson('/api/tenants/acme/cart/items/'.$response->json('data.items.0.id'), [
                'cantidad' => 4,
            ])
            ->assertUnprocessable()
            ->assertJsonValidationErrors('cantidad');

        $this->assertDatabaseHas('carrito_items', [
            'id' => $response->json('data.items.0.id'),
            'cantidad' => 2,
        ]);
    }

    public function test_guest_cart_does_not_apply_a_user_purchase_limit(): void
    {
        $tenant = $this->createTenant('acme');
        $item = $this->createDirectItem($tenant, 20, '10.00');
        $item->update(['max_units_per_user' => 1]);

        $this->postJson('/api/tenants/acme/cart/items', [
            'catalog_item_id' => $item->id,
            'cantidad' => 2,
        ])
            ->assertOk()
            ->assertJsonPath('data.items.0.cantidad', 2);
    }

    public function test_it_updates_and_removes_an_item_using_its_selected_inventory(): void
    {
        $tenant = $this->createTenant('acme');
        [$item, $variant] = $this->createVariantItem($tenant, 10, '15.00');
        $createResponse = $this->postJson('/api/tenants/acme/cart/items', [
            'catalog_item_id' => $item->id,
            'variant_id' => $variant->id,
            'cantidad' => 2,
        ]);
        $guestToken = $createResponse->getCookie('guest_token', false)?->getValue();
        $cartItemId = $createResponse->json('data.items.0.id');

        $this->call(
            'PATCH',
            "/api/tenants/acme/cart/items/{$cartItemId}",
            [],
            ['guest_token' => $guestToken],
            [],
            ['HTTP_Accept' => 'application/json', 'CONTENT_TYPE' => 'application/json'],
            json_encode(['cantidad' => 5]),
        )
            ->assertOk()
            ->assertJsonPath('data.items.0.cantidad', 5);

        $this->assertDatabaseHas('inventories', [
            'id' => $variant->inventory_id,
            'reserved_stock' => 5,
        ]);

        $this->call(
            'DELETE',
            "/api/tenants/acme/cart/items/{$cartItemId}",
            [],
            ['guest_token' => $guestToken],
            [],
            ['HTTP_Accept' => 'application/json'],
        )
            ->assertOk()
            ->assertJsonPath('data.items', []);

        $this->assertDatabaseHas('inventories', [
            'id' => $variant->inventory_id,
            'reserved_stock' => 0,
        ]);
        $this->assertDatabaseHas('stock_reservations', [
            'cart_item_id' => null,
            'inventory_id' => $variant->inventory_id,
            'quantity' => 0,
            'status' => 'released',
        ]);
    }

    public function test_it_changes_an_item_variant_and_moves_the_stock_reservation(): void
    {
        $tenant = $this->createTenant('acme');
        [$item, $firstVariant] = $this->createVariantItem($tenant, 10, '15.00');
        $secondInventory = Inventory::query()->create(['real_stock' => 2]);
        $secondVariant = $item->variants()->create([
            'inventory_id' => $secondInventory->id,
            'precio' => '20.00',
        ]);
        $createResponse = $this->postJson('/api/tenants/acme/cart/items', [
            'catalog_item_id' => $item->id,
            'variant_id' => $firstVariant->id,
            'cantidad' => 2,
        ]);
        $guestToken = $createResponse->getCookie('guest_token', false)?->getValue();
        $cartItemId = $createResponse->json('data.items.0.id');

        $this->call(
            'PATCH',
            "/api/tenants/acme/cart/items/{$cartItemId}",
            [],
            ['guest_token' => $guestToken],
            [],
            ['HTTP_Accept' => 'application/json', 'CONTENT_TYPE' => 'application/json'],
            json_encode(['cantidad' => 2, 'variant_id' => $secondVariant->id]),
        )
            ->assertOk()
            ->assertJsonPath('data.items.0.variant_id', $secondVariant->id)
            ->assertJsonPath('data.items.0.precio_unitario', '20.00')
            ->assertJsonPath('data.items.0.variant.id', $secondVariant->id)
            ->assertJsonPath('data.items.0.variant.precio', '20.00')
            ->assertJsonPath('data.items.0.variant.stock_tecnico', 0)
            ->assertJsonMissingPath('data.items.0.product');

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

    public function test_changing_to_a_variant_already_in_the_cart_merges_both_rows(): void
    {
        $tenant = $this->createTenant('acme');
        [$item, $firstVariant] = $this->createVariantItem($tenant, 10, '15.00');
        $secondInventory = Inventory::query()->create(['real_stock' => 10]);
        $secondVariant = $item->variants()->create(['inventory_id' => $secondInventory->id]);

        $firstResponse = $this->postJson('/api/tenants/acme/cart/items', [
            'catalog_item_id' => $item->id,
            'variant_id' => $firstVariant->id,
            'cantidad' => 2,
        ]);
        $guestToken = $firstResponse->getCookie('guest_token', false)?->getValue();
        $firstCartItemId = $firstResponse->json('data.items.0.id');

        $this->call(
            'POST',
            '/api/tenants/acme/cart/items',
            [],
            ['guest_token' => $guestToken],
            [],
            ['HTTP_Accept' => 'application/json', 'CONTENT_TYPE' => 'application/json'],
            json_encode([
                'catalog_item_id' => $item->id,
                'variant_id' => $secondVariant->id,
                'cantidad' => 3,
            ]),
        )->assertOk();

        $this->call(
            'PATCH',
            "/api/tenants/acme/cart/items/{$firstCartItemId}",
            [],
            ['guest_token' => $guestToken],
            [],
            ['HTTP_Accept' => 'application/json', 'CONTENT_TYPE' => 'application/json'],
            json_encode(['cantidad' => 2, 'variant_id' => $secondVariant->id]),
        )
            ->assertOk()
            ->assertJsonCount(1, 'data.items')
            ->assertJsonPath('data.items.0.variant_id', $secondVariant->id)
            ->assertJsonPath('data.items.0.cantidad', 5);

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

    public function test_quantity_and_remove_policy_hides_variants_and_rejects_variant_changes(): void
    {
        $tenant = $this->createTenant('acme');
        $tenant->update(['cart_editing_policy' => 'quantity_and_remove']);
        [$item, $firstVariant] = $this->createVariantItem($tenant, 10, '15.00');
        $secondInventory = Inventory::query()->create(['real_stock' => 10]);
        $secondVariant = $item->variants()->create(['inventory_id' => $secondInventory->id]);
        $createResponse = $this->postJson('/api/tenants/acme/cart/items', [
            'catalog_item_id' => $item->id,
            'variant_id' => $firstVariant->id,
            'cantidad' => 1,
        ])->assertJsonMissingPath('data.items.0.variants');
        $guestToken = $createResponse->getCookie('guest_token', false)?->getValue();
        $cartItemId = $createResponse->json('data.items.0.id');

        $this->call(
            'PATCH',
            "/api/tenants/acme/cart/items/{$cartItemId}",
            [],
            ['guest_token' => $guestToken],
            [],
            ['HTTP_Accept' => 'application/json', 'CONTENT_TYPE' => 'application/json'],
            json_encode(['cantidad' => 2]),
        )->assertOk()->assertJsonPath('data.items.0.cantidad', 2);

        $this->call(
            'PATCH',
            "/api/tenants/acme/cart/items/{$cartItemId}",
            [],
            ['guest_token' => $guestToken],
            [],
            ['HTTP_Accept' => 'application/json', 'CONTENT_TYPE' => 'application/json'],
            json_encode(['cantidad' => 2, 'variant_id' => $secondVariant->id]),
        )->assertUnprocessable()->assertJsonValidationErrors('variant_id');

        $this->call(
            'DELETE',
            "/api/tenants/acme/cart/items/{$cartItemId}",
            [],
            ['guest_token' => $guestToken],
            [],
            ['HTTP_Accept' => 'application/json'],
        )->assertOk()->assertJsonPath('data.items', []);
    }

    public function test_disabled_policy_rejects_quantity_changes_and_removal(): void
    {
        $tenant = $this->createTenant('acme');
        $tenant->update(['cart_editing_policy' => 'disabled']);
        $item = $this->createDirectItem($tenant, 10, '15.00');
        $createResponse = $this->postJson('/api/tenants/acme/cart/items', [
            'catalog_item_id' => $item->id,
            'cantidad' => 1,
        ])->assertOk();
        $guestToken = $createResponse->getCookie('guest_token', false)?->getValue();
        $cartItemId = $createResponse->json('data.items.0.id');

        $this->call(
            'PATCH',
            "/api/tenants/acme/cart/items/{$cartItemId}",
            [],
            ['guest_token' => $guestToken],
            [],
            ['HTTP_Accept' => 'application/json', 'CONTENT_TYPE' => 'application/json'],
            json_encode(['cantidad' => 2]),
        )->assertUnprocessable()->assertJsonValidationErrors('cantidad');

        $this->call(
            'DELETE',
            "/api/tenants/acme/cart/items/{$cartItemId}",
            [],
            ['guest_token' => $guestToken],
            [],
            ['HTTP_Accept' => 'application/json'],
        )->assertUnprocessable()->assertJsonValidationErrors('cart_item');
    }

    public function test_it_requires_a_variant_when_the_item_has_variant_inventory(): void
    {
        $tenant = $this->createTenant('acme');
        [$item] = $this->createVariantItem($tenant, 10, '10.00');

        $this->postJson('/api/tenants/acme/cart/items', [
            'catalog_item_id' => $item->id,
            'cantidad' => 1,
        ])->assertUnprocessable()->assertJsonValidationErrors('variant_id');
    }

    public function test_it_rejects_a_variant_from_another_item_or_tenant(): void
    {
        $acme = $this->createTenant('acme');
        $globex = $this->createTenant('globex');
        [$acmeItem] = $this->createVariantItem($acme, 10, '10.00');
        [, $globexVariant] = $this->createVariantItem($globex, 10, '20.00');

        $this->postJson('/api/tenants/acme/cart/items', [
            'catalog_item_id' => $acmeItem->id,
            'variant_id' => $globexVariant->id,
            'cantidad' => 1,
        ])->assertUnprocessable()->assertJsonValidationErrors('variant_id');
    }

    public function test_unlimited_inventory_can_be_reserved_and_released(): void
    {
        $tenant = $this->createTenant('acme');
        $item = $this->createDirectItem(
            $tenant,
            0,
            '10.00',
            InventoryPolicy::Unlimited,
        );

        $response = $this->postJson('/api/tenants/acme/cart/items', [
            'catalog_item_id' => $item->id,
            'cantidad' => 100,
        ])->assertOk();

        $guestToken = $response->getCookie('guest_token', false)?->getValue();
        $cartItemId = $response->json('data.items.0.id');

        $this->assertDatabaseHas('inventories', [
            'id' => $item->inventory_id,
            'real_stock' => 0,
            'reserved_stock' => 100,
        ]);

        $this->call(
            'DELETE',
            "/api/tenants/acme/cart/items/{$cartItemId}",
            [],
            ['guest_token' => $guestToken],
            [],
            ['HTTP_Accept' => 'application/json'],
        )
            ->assertOk();

        $this->assertDatabaseHas('inventories', [
            'id' => $item->inventory_id,
            'reserved_stock' => 0,
        ]);
    }

    private function createDirectItem(
        Tenant $tenant,
        int $stock,
        string $price,
        InventoryPolicy $policy = InventoryPolicy::Tracked,
    ): CatalogItem {
        $inventory = Inventory::query()->create(['real_stock' => $stock]);

        return CatalogItem::query()->create([
            'tenant_code' => $tenant->codigo,
            'inventory_id' => $inventory->id,
            'slug' => 'item-'.$tenant->codigo.'-'.CatalogItem::query()->count(),
            'nombre' => 'Item '.$tenant->codigo,
            'precio' => $price,
            'inventory_policy' => $policy,
        ]);
    }

    /** @return array{CatalogItem, Variant} */
    private function createVariantItem(Tenant $tenant, int $stock, string $price): array
    {
        $item = CatalogItem::query()->create([
            'tenant_code' => $tenant->codigo,
            'inventory_id' => null,
            'slug' => 'variant-item-'.$tenant->codigo.'-'.CatalogItem::query()->count(),
            'nombre' => 'Variant item '.$tenant->codigo,
            'precio' => $price,
            'inventory_policy' => InventoryPolicy::Tracked,
        ]);
        $inventory = Inventory::query()->create(['real_stock' => $stock]);
        $variant = $item->variants()->create(['inventory_id' => $inventory->id]);

        return [$item, $variant];
    }

    private function createPurchaseItem(
        Tenant $tenant,
        User $user,
        CatalogItem $item,
        int $quantity,
    ): PurchaseItem {
        $purchase = Purchase::query()->create([
            'tenant_codigo' => $tenant->codigo,
            'user_id' => $user->id,
            'status' => Purchase::STATUS_PAID,
            'total' => (float) $item->precio * $quantity,
        ]);

        return $purchase->items()->create([
            'source_catalog_item_id' => $item->id,
            'source_variant_id' => null,
            'nombre' => $item->nombre,
            'slug' => $item->slug,
            'item_nombre' => $item->nombre,
            'variant_attributes' => [],
            'cantidad' => $quantity,
            'precio_unitario' => $item->precio,
            'total' => (float) $item->precio * $quantity,
        ]);
    }

    private function createTenant(string $code): Tenant
    {
        $headerLogo = $this->createAttachment("{$code}-header");
        $footerLogo = $this->createAttachment("{$code}-footer");

        return Tenant::query()->create([
            'codigo' => $code,
            'nombre' => ucfirst($code),
            'dominio' => "{$code}.local",
            'primary_color' => '#000000',
            'secondary_color' => '#000000',
            'danger_color' => '#000000',
            'success_color' => '#000000',
            'header_bg_color' => '#000000',
            'footer_bg_color' => '#000000',
            'header_logo_id' => $headerLogo->id,
            'footer_logo_id' => $footerLogo->id,
        ]);
    }

    private function createAttachment(string $name): Attachment
    {
        return Attachment::query()->create([
            'path' => "test/{$name}.png",
            'filename' => "{$name}.png",
            'type' => AttachmentType::Image,
            'mime_type' => 'image/png',
        ]);
    }
}
