<?php

namespace Tests\Feature\Catalog;

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\Attribute;
use App\Domains\Catalog\Models\CatalogItem;
use App\Domains\Catalog\Models\Inventory;
use App\Domains\Catalog\Models\ItemAttribute;
use App\Domains\Catalog\Models\Variant;
use App\Domains\Shared\Enums\FieldType;
use App\Domains\Tenant\Models\Tenant;
use Illuminate\Foundation\Testing\RefreshDatabase;
use Illuminate\Support\Facades\Storage;
use Tests\TestCase;

class CatalogItemDetailControllerTest extends TestCase
{
    use RefreshDatabase;

    public function test_it_returns_item_images_and_stock_when_the_item_has_no_variants(): void
    {
        Storage::fake('s3');
        $tenant = $this->createTenant('detail-direct');
        $inventory = Inventory::query()->create([
            'real_stock' => 10,
            'reserved_stock' => 3,
        ]);
        $item = $this->createItem($tenant, 'Direct item', $inventory);
        $itemImage = $this->createAttachment('direct-item');
        $item->attachments()->attach($itemImage, ['orden' => 0]);

        $response = $this->getJson(
            "/api/tenants/{$tenant->codigo}/catalog-items/{$item->id}"
        );

        $response
            ->assertOk()
            ->assertJsonPath('data.maximum_addable_quantity', 7)
            ->assertJsonMissingPath('data.stock_tecnico')
            ->assertJsonCount(0, 'data.variants')
            ->assertJsonCount(1, 'data.images');
        $response->assertJsonMissingPath('data.selected_variant');
        $this->assertStringContainsString($itemImage->path, $response->json('data.images.0'));
    }

    public function test_it_omits_unavailable_variants_and_selects_the_first_available_one(): void
    {
        Storage::fake('s3');
        $tenant = $this->createTenant('detail-default');
        $item = $this->createItem($tenant, 'Variant item');
        $itemImage = $this->createAttachment('item-image');
        $item->attachments()->attach($itemImage, ['orden' => 0]);

        $firstVariant = $this->createVariant($item, 0, 0);
        $secondVariant = $this->createVariant($item, 8, 2);
        $firstImage = $this->createAttachment('first-variant');
        $secondImage = $this->createAttachment('second-variant');
        $firstVariant->attachments()->attach($firstImage, ['orden' => 0]);
        $secondVariant->attachments()->attach($secondImage, ['orden' => 0]);

        $response = $this->getJson(
            "/api/tenants/{$tenant->codigo}/catalog-items/{$item->id}"
        );

        $response
            ->assertOk()
            ->assertJsonCount(1, 'data.variants')
            ->assertJsonPath('data.variants.0.id', $secondVariant->id)
            ->assertJsonPath('data.selected_variant.id', $secondVariant->id)
            ->assertJsonPath('data.selected_variant.maximum_addable_quantity', 6)
            ->assertJsonMissingPath('data.selected_variant.stock_tecnico')
            ->assertJsonCount(1, 'data.selected_variant.images');
        $response
            ->assertJsonMissingPath('data.stock_tecnico')
            ->assertJsonMissingPath('data.images');
        $this->assertNotContains(
            $firstVariant->id,
            collect($response->json('data.variants'))->pluck('id')->all(),
        );
        $this->assertStringContainsString($secondImage->path, $response->json('data.selected_variant.images.0'));
        $this->assertStringNotContainsString($firstImage->path, $response->json('data.selected_variant.images.0'));
        $this->assertStringNotContainsString($itemImage->path, $response->json('data.selected_variant.images.0'));

        $this->getJson(
            "/api/tenants/{$tenant->codigo}/catalog-items/{$item->id}?variant_id={$firstVariant->id}"
        )->assertNotFound();
    }

    public function test_it_does_not_return_an_out_of_stock_item(): void
    {
        $tenant = $this->createTenant('detail-out-of-stock');
        $inventory = Inventory::query()->create([
            'real_stock' => 5,
            'reserved_stock' => 5,
        ]);
        $item = $this->createItem($tenant, 'Sold out item', $inventory);

        $this->getJson("/api/tenants/{$tenant->codigo}/catalog-items/{$item->id}")
            ->assertNotFound();
    }

    public function test_it_selects_the_requested_variant_and_lists_variant_values_and_stock(): void
    {
        Storage::fake('s3');
        $tenant = $this->createTenant('detail-requested');
        $item = $this->createItem($tenant, 'Shirt');
        $size = Attribute::query()->create([
            'tenant_codigo' => $tenant->codigo,
            'codigo' => 'size',
            'nombre' => 'Size',
            'type' => FieldType::String,
        ]);
        $itemSize = ItemAttribute::query()->create([
            'catalog_item_id' => $item->id,
            'attribute_id' => $size->id,
        ]);
        $size->options()->createMany([
            ['value' => 'S', 'label' => 'Small', 'sort_order' => 0],
            ['value' => 'M', 'label' => 'Medium', 'sort_order' => 1],
            ['value' => 'L', 'label' => 'Large', 'sort_order' => 2],
        ]);
        $firstVariant = $this->createVariant($item, 5, 1);
        $secondVariant = $this->createVariant($item, 9, 2);
        $firstVariant->definitions()->create([
            'item_attribute_id' => $itemSize->id,
            'value' => 'S',
        ]);
        $secondVariant->definitions()->create([
            'item_attribute_id' => $itemSize->id,
            'value' => 'M',
        ]);
        $secondImage = $this->createAttachment('selected-variant');
        $secondVariant->attachments()->attach($secondImage, ['orden' => 0]);

        $response = $this->getJson(
            "/api/tenants/{$tenant->codigo}/catalog-items/{$item->id}?variant_id={$secondVariant->id}"
        );

        $response
            ->assertOk()
            ->assertJsonPath('data.variants.0.id', $firstVariant->id)
            ->assertJsonPath('data.variants.0.maximum_addable_quantity', 4)
            ->assertJsonPath('data.variants.0.values.size.value', 'S')
            ->assertJsonPath('data.variants.0.values.size.label', 'Small')
            ->assertJsonPath('data.variants.1.id', $secondVariant->id)
            ->assertJsonPath('data.variants.1.maximum_addable_quantity', 7)
            ->assertJsonPath('data.variants.1.values.size.value', 'M')
            ->assertJsonPath('data.variants.1.values.size.label', 'Medium')
            ->assertJsonPath('data.attributes.0.codigo', 'size')
            ->assertJsonPath('data.attributes.0.options.0.value', 'S')
            ->assertJsonPath('data.attributes.0.options.1.value', 'M')
            ->assertJsonCount(2, 'data.attributes.0.options')
            ->assertJsonPath('data.selected_variant.id', $secondVariant->id)
            ->assertJsonPath('data.selected_variant.maximum_addable_quantity', 7)
            ->assertJsonPath('data.selected_variant.values.size.value', 'M')
            ->assertJsonPath('data.selected_variant.values.size.label', 'Medium')
            ->assertJsonCount(1, 'data.selected_variant.images');
        $response
            ->assertJsonMissingPath('data.stock_tecnico')
            ->assertJsonMissingPath('data.images')
            ->assertJsonMissingPath('data.variants.0.images')
            ->assertJsonMissingPath('data.variants.1.images');
        $this->assertStringContainsString(
            $secondImage->path,
            $response->json('data.selected_variant.images.0'),
        );
    }

    public function test_it_rejects_an_invalid_or_foreign_variant(): void
    {
        $tenant = $this->createTenant('detail-invalid');
        $item = $this->createItem($tenant, 'Requested item');
        $otherItem = $this->createItem($tenant, 'Other item');
        $foreignVariant = $this->createVariant($otherItem, 5, 0);

        $this->getJson(
            "/api/tenants/{$tenant->codigo}/catalog-items/{$item->id}?variant_id=abc"
        )->assertUnprocessable()->assertJsonValidationErrors('variant_id');

        $this->getJson(
            "/api/tenants/{$tenant->codigo}/catalog-items/{$item->id}?variant_id={$foreignVariant->id}"
        )->assertNotFound();
    }

    public function test_it_returns_null_technical_stock_for_unlimited_variants(): void
    {
        $tenant = $this->createTenant('detail-unlimited');
        $item = $this->createItem($tenant, 'Unlimited item', policy: InventoryPolicy::Unlimited);
        $variant = $this->createVariant($item, 0, 20);

        $this->getJson("/api/tenants/{$tenant->codigo}/catalog-items/{$item->id}")
            ->assertOk()
            ->assertJsonPath('data.selected_variant.id', $variant->id)
            ->assertJsonPath('data.selected_variant.maximum_addable_quantity', null)
            ->assertJsonMissingPath('data.stock_tecnico')
            ->assertJsonPath('data.variants.0.maximum_addable_quantity', null)
            ->assertJsonMissingPath('data.selected_variant.stock_tecnico')
            ->assertJsonMissingPath('data.variants.0.stock_tecnico');
    }

    public function test_it_exposes_event_dates_as_a_dynamic_variant_attribute(): void
    {
        $tenant = $this->createTenant('detail-event-date');
        $tenant->update([
            'event_title' => 'Festival',
            'event_location' => 'Rosario',
        ]);
        $eventDate = $tenant->eventDates()->create([
            'date' => '2026-10-09',
            'time_start' => '09:00',
            'time_end' => '18:00',
        ]);
        $unusedEventDate = $tenant->eventDates()->create([
            'date' => '2026-10-10',
            'time_start' => '10:00',
            'time_end' => '19:00',
        ]);
        $item = $this->createItem($tenant, 'Entry');
        $attribute = Attribute::query()->create([
            'tenant_codigo' => $tenant->codigo,
            'codigo' => 'event_date',
            'nombre' => 'Fecha',
            'is_required' => true,
            'type' => FieldType::EventDate,
        ]);
        $item->itemAttributes()->create(['attribute_id' => $attribute->id]);
        $variant = $this->createVariant($item, 10, 0);
        $variant->update(['event_date_id' => $eventDate->id]);

        $this->getJson("/api/tenants/{$tenant->codigo}/catalog-items/{$item->id}")
            ->assertOk()
            ->assertJsonPath('data.attributes.0.id', $attribute->id)
            ->assertJsonPath('data.attributes.0.codigo', 'event_date')
            ->assertJsonPath('data.attributes.0.type', 'event_date')
            ->assertJsonCount(2, 'data.attributes.0.options')
            ->assertJsonPath('data.attributes.0.options.0.id', $eventDate->id)
            ->assertJsonPath('data.attributes.0.options.0.value', (string) $eventDate->id)
            ->assertJsonPath('data.attributes.0.options.0.label', '09/10/2026')
            ->assertJsonPath('data.attributes.0.options.0.validity_time_id', $eventDate->validity_time_id)
            ->assertJsonPath('data.attributes.0.options.0.validity_time.type', 'fixed_window')
            ->assertJsonPath('data.attributes.0.options.1.id', $unusedEventDate->id)
            ->assertJsonPath('data.attributes.0.options.1.value', (string) $unusedEventDate->id)
            ->assertJsonPath('data.variants.0.values.event_date.value', (string) $eventDate->id)
            ->assertJsonPath(
                'data.variants.0.values.event_date.label',
                '09/10/2026',
            );

        $this->assertDatabaseCount('attribute_options', 0);
    }

    public function test_it_orders_item_attributes_by_sort_order_and_then_attribute_label(): void
    {
        $tenant = $this->createTenant('detail-attribute-order');
        $item = $this->createItem($tenant, 'Ordered attributes');
        $variant = $this->createVariant($item, 10, 0);

        $attributes = collect([
            ['code' => 'zeta', 'label' => 'Zeta', 'sort_order' => 2],
            ['code' => 'priority', 'label' => 'Priority', 'sort_order' => 1],
            ['code' => 'alpha', 'label' => 'Alpha', 'sort_order' => 2],
        ])->mapWithKeys(function (array $data) use ($tenant, $item): array {
            $attribute = Attribute::query()->create([
                'tenant_codigo' => $tenant->codigo,
                'codigo' => $data['code'],
                'nombre' => $data['label'],
                'type' => FieldType::String,
            ]);
            $itemAttribute = $item->itemAttributes()->create([
                'attribute_id' => $attribute->id,
                'sort_order' => $data['sort_order'],
            ]);

            return [$data['code'] => $itemAttribute];
        });

        foreach (['zeta', 'priority', 'alpha'] as $code) {
            $variant->definitions()->create([
                'item_attribute_id' => $attributes[$code]->id,
                'value' => $code,
            ]);
        }

        $response = $this->getJson("/api/tenants/{$tenant->codigo}/catalog-items/{$item->id}")
            ->assertOk()
            ->assertJsonPath('data.attributes.0.codigo', 'priority')
            ->assertJsonPath('data.attributes.0.sort_order', 1)
            ->assertJsonPath('data.attributes.1.codigo', 'alpha')
            ->assertJsonPath('data.attributes.2.codigo', 'zeta');

        $this->assertSame(
            ['priority', 'alpha', 'zeta'],
            array_keys($response->json('data.variants.0.values')),
        );
    }

    public function test_it_exposes_whether_an_item_attribute_should_be_shown_in_the_selector(): void
    {
        $tenant = $this->createTenant('detail-hidden-attribute');
        $item = $this->createItem($tenant, 'Hidden attribute');
        $attribute = Attribute::query()->create([
            'tenant_codigo' => $tenant->codigo,
            'codigo' => 'internal_type',
            'nombre' => 'Internal type',
            'type' => FieldType::String,
        ]);
        $item->itemAttributes()->create([
            'attribute_id' => $attribute->id,
            'show_in_selector' => false,
        ]);

        $this->getJson("/api/tenants/{$tenant->codigo}/catalog-items/{$item->id}")
            ->assertOk()
            ->assertJsonPath('data.attributes.0.show_in_selector', false);
    }

    public function test_it_resolves_available_variant_options_from_partial_selections(): void
    {
        $tenant = $this->createTenant('variant-options');
        $item = $this->createItem($tenant, 'Numbered entry');
        $sector = Attribute::query()->create([
            'tenant_codigo' => $tenant->codigo,
            'codigo' => 'sector',
            'nombre' => 'Sector',
            'type' => FieldType::Select,
        ]);
        $seat = Attribute::query()->create([
            'tenant_codigo' => $tenant->codigo,
            'codigo' => 'seat',
            'nombre' => 'Seat',
            'type' => FieldType::Select,
        ]);
        $itemSector = $item->itemAttributes()->create([
            'attribute_id' => $sector->id,
            'sort_order' => 0,
        ]);
        $itemSeat = $item->itemAttributes()->create([
            'attribute_id' => $seat->id,
            'sort_order' => 1,
        ]);
        $first = $this->createVariant($item, 1, 0);
        $second = $this->createVariant($item, 1, 0);
        $third = $this->createVariant($item, 1, 0);

        foreach ([[$first, 'A', '1'], [$second, 'A', '2'], [$third, 'B', '3']] as [$variant, $sectorValue, $seatValue]) {
            $variant->definitions()->createMany([
                ['item_attribute_id' => $itemSector->id, 'value' => $sectorValue],
                ['item_attribute_id' => $itemSeat->id, 'value' => $seatValue],
            ]);
        }

        $this->postJson(
            "/api/tenants/{$tenant->codigo}/catalog-items/{$item->id}/variant-options",
            [
                'selected_values' => ['sector' => 'A'],
            ],
        )
            ->assertOk()
            ->assertJsonPath('data.valid', true)
            ->assertJsonPath('data.resolved_variant', null)
            ->assertJsonCount(3, 'data.variants')
            ->assertJsonPath('data.variants.0.id', $first->id)
            ->assertJsonPath('data.variants.0.values.sector.value', 'A')
            ->assertJsonPath('data.variants.0.values.seat.value', '1')
            ->assertJsonCount(2, 'data.selectors')
            ->assertJsonPath('data.selectors.0.key', 'sector')
            ->assertJsonCount(2, 'data.selectors.0.options')
            ->assertJsonCount(2, 'data.selectors.1.options')
            ->assertJsonPath('data.selectors.1.options.0.value', '1')
            ->assertJsonPath('data.available_variant_count', 3)
            ->assertJsonPath('data.matching_variant_count', 2);

        $this->postJson(
            "/api/tenants/{$tenant->codigo}/catalog-items/{$item->id}/variant-options",
            ['selected_values' => ['sector' => 'A', 'seat' => '1']],
        )
            ->assertOk()
            ->assertJsonPath('data.resolved_variant.id', $first->id)
            ->assertJsonPath('data.resolved_variant.values.sector.value', 'A');
    }

    public function test_variant_options_restore_canonical_values_from_the_reserved_cart_item(): void
    {
        $tenant = $this->createTenant('reserved-variant-options');
        $item = $this->createItem($tenant, 'Reserved numbered entry');
        $sector = Attribute::query()->create([
            'tenant_codigo' => $tenant->codigo,
            'codigo' => 'sector',
            'nombre' => 'Sector',
            'type' => FieldType::Select,
        ]);
        $seat = Attribute::query()->create([
            'tenant_codigo' => $tenant->codigo,
            'codigo' => 'seat',
            'nombre' => 'Seat',
            'type' => FieldType::Select,
        ]);
        $itemSector = $item->itemAttributes()->create([
            'attribute_id' => $sector->id,
            'sort_order' => 0,
        ]);
        $itemSeat = $item->itemAttributes()->create([
            'attribute_id' => $seat->id,
            'sort_order' => 1,
        ]);
        $variant = $this->createVariant($item, 1, 0);
        $variant->definitions()->createMany([
            ['item_attribute_id' => $itemSector->id, 'value' => 'VIP'],
            ['item_attribute_id' => $itemSeat->id, 'value' => 'A-12'],
        ]);
        $user = User::factory()->create();
        $cart = Cart::query()->create([
            'tenant_codigo' => $tenant->codigo,
            'user_id' => $user->id,
            'status' => 'active',
        ]);
        $cartItem = $cart->addItem($item->id, $variant->id, 1);

        $this->actingAs($user, 'sanctum')
            ->postJson(
                "/api/tenants/{$tenant->codigo}/catalog-items/{$item->id}/variant-options",
                [
                    'selected_values' => [],
                    'cart_item_id' => $cartItem->id,
                ],
            )
            ->assertOk()
            ->assertJsonPath('data.selected_values.sector', 'VIP')
            ->assertJsonPath('data.selected_values.seat', 'A-12')
            ->assertJsonPath('data.resolved_variant.id', $variant->id);
    }

    private function createItem(
        Tenant $tenant,
        string $name,
        ?Inventory $inventory = null,
        InventoryPolicy $policy = InventoryPolicy::Tracked,
    ): CatalogItem {
        return CatalogItem::query()->create([
            'tenant_code' => $tenant->codigo,
            'inventory_id' => $inventory?->id,
            'slug' => str($name)->slug()->toString(),
            'nombre' => $name,
            'descripcion' => "{$name} description",
            'precio' => 100,
            'inventory_policy' => $policy,
        ]);
    }

    private function createVariant(CatalogItem $item, int $realStock, int $reservedStock): Variant
    {
        $inventory = Inventory::query()->create([
            'real_stock' => $realStock,
            'reserved_stock' => $reservedStock,
        ]);

        return $item->variants()->create(['inventory_id' => $inventory->id]);
    }

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