<?php

namespace Tests\Feature\Cart;

use App\Domains\Attachable\Enums\AttachmentType;
use App\Domains\Attachable\Models\Attachment;
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\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
    {
        $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.cantidad', 2)
            ->assertJsonPath('data.items.0.precio_unitario', '49.90')
            ->assertJsonPath('data.items.0.product.nombre', 'Item acme')
            ->assertJsonPath('data.subtotal', '99.80');

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

    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.cantidad', 5)
            ->assertJsonPath('data.subtotal', '125.00');

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

    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,
        ]);
    }

    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 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',
        ]);
    }
}
