<?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\FeaturedGroupSource;
use App\Domains\Catalog\Enums\GroupLayout;
use App\Domains\Catalog\Enums\ProductLayout;
use App\Domains\Catalog\Models\CatalogItem;
use App\Domains\Catalog\Models\Category;
use App\Domains\Catalog\Models\FeaturedGroup;
use App\Domains\Catalog\Models\Inventory;
use App\Domains\Tenant\Models\Tenant;
use Illuminate\Foundation\Testing\RefreshDatabase;
use Illuminate\Support\Facades\Storage;
use Tests\TestCase;

class CatalogControllerTest extends TestCase
{
    use RefreshDatabase;

    public function test_row_and_column_with_cart_return_item_details_variants_and_maximum_quantity(): void
    {
        $tenant = $this->createTenant('catalog-index');
        $row = $this->createGroup($tenant, ProductLayout::Row, 'Row', 2);
        $cart = $this->createGroup(
            $tenant,
            ProductLayout::ColumnWithCart,
            'Cart',
            1,
            GroupLayout::SimpleVertical,
        );

        $directInventory = Inventory::query()->create([
            'real_stock' => 10,
            'reserved_stock' => 2,
        ]);
        $directItem = $this->createItem($tenant, 'Direct', $directInventory);
        $row->featuredItems()->create(['catalog_item_id' => $directItem->id]);

        $variantItem = $this->createItem($tenant, 'Variants');
        $firstInventory = Inventory::query()->create([
            'real_stock' => 5,
            'reserved_stock' => 1,
        ]);
        $secondInventory = Inventory::query()->create([
            'real_stock' => 4,
            'reserved_stock' => 1,
        ]);
        $unavailableInventory = Inventory::query()->create([
            'real_stock' => 2,
            'reserved_stock' => 2,
        ]);
        $variantItem->variants()->create(['inventory_id' => $firstInventory->id]);
        $variantItem->variants()->create(['inventory_id' => $secondInventory->id]);
        $unavailableVariant = $variantItem->variants()->create([
            'inventory_id' => $unavailableInventory->id,
        ]);
        $cart->featuredItems()->create(['catalog_item_id' => $variantItem->id]);

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

        $response
            ->assertOk()
            ->assertJsonCount(2)
            ->assertJsonPath('0.title', 'Cart')
            ->assertJsonPath('0.layout', ProductLayout::ColumnWithCart->value)
            ->assertJsonPath('0.group_layout', GroupLayout::SimpleVertical->value)
            ->assertJsonPath('0.items.0.nombre', 'Variants')
            ->assertJsonPath('0.items.0.descripcion', 'Variants description')
            ->assertJsonPath('0.items.0.precio', '100.00')
            ->assertJsonPath('0.items.0.maximum_addable_quantity', 7)
            ->assertJsonCount(2, '0.items.0.variants')
            ->assertJsonPath('0.items.0.variants.0.maximum_addable_quantity', 4)
            ->assertJsonPath('0.items.0.variants.1.maximum_addable_quantity', 3)
            ->assertJsonPath('1.title', 'Row')
            ->assertJsonPath('1.items.data.0.maximum_addable_quantity', 8)
            ->assertJsonMissingPath('1.items.data.0.stock_tecnico')
            ->assertJsonCount(0, '1.items.data.0.variants');

        $this->assertNotContains(
            $unavailableVariant->id,
            collect($response->json('0.items.0.variants'))->pluck('id')->all(),
        );
    }

    public function test_maximum_addable_quantity_shares_the_authenticated_user_quota_between_variants(): void
    {
        $tenant = $this->createTenant('catalog-allowance');
        $group = $this->createGroup(
            $tenant,
            ProductLayout::ColumnWithCart,
            'Allowances',
            groupLayout: GroupLayout::Simple,
        );
        $user = User::factory()->create();
        $item = $this->createItem($tenant, 'Limited variants');
        $item->update(['max_units_per_user' => 3]);
        $firstVariant = $item->variants()->create([
            'inventory_id' => Inventory::query()->create(['real_stock' => 10])->id,
        ]);
        $secondVariant = $item->variants()->create([
            'inventory_id' => Inventory::query()->create(['real_stock' => 10])->id,
        ]);
        $group->featuredItems()->create(['catalog_item_id' => $item->id]);

        $cart = Cart::query()->create([
            'tenant_codigo' => $tenant->codigo,
            'user_id' => $user->id,
            'status' => 'active',
        ]);
        $cart->addItem($item->id, $firstVariant->id, 2);
        $cart->addItem($item->id, $secondVariant->id, 1);

        $this->actingAs($user, 'sanctum')
            ->getJson("/api/tenants/{$tenant->codigo}/catalog")
            ->assertOk()
            ->assertJsonPath('0.items.0.variants.0.maximum_addable_quantity', 0)
            ->assertJsonPath('0.items.0.variants.1.maximum_addable_quantity', 0)
            ->assertJsonPath(
                '0.items.0.variants.0.unavailable_message',
                'Alcanzaste el cupo máximo permitido para este producto.',
            )
            ->assertJsonPath(
                '0.items.0.variants.1.unavailable_message',
                'Alcanzaste el cupo máximo permitido para este producto.',
            )
            ->assertJsonMissingPath('0.items.0.variants.0.stock_tecnico')
            ->assertJsonMissingPath('0.items.0.variants.1.stock_tecnico');
    }

    public function test_it_excludes_out_of_stock_items(): void
    {
        $tenant = $this->createTenant('catalog-available-variants');
        $group = $this->createGroup(
            $tenant,
            ProductLayout::ColumnWithCart,
            'Available variants',
            groupLayout: GroupLayout::SimpleVertical,
        );

        $unavailableItem = $this->createItem($tenant, 'Unavailable');
        $unavailableInventory = Inventory::query()->create([
            'real_stock' => 4,
            'reserved_stock' => 4,
        ]);
        $unavailableItem->variants()->create(['inventory_id' => $unavailableInventory->id]);
        $group->featuredItems()->create(['catalog_item_id' => $unavailableItem->id]);

        $availableItem = $this->createItem($tenant, 'Available');
        $availableInventory = Inventory::query()->create([
            'real_stock' => 4,
            'reserved_stock' => 3,
        ]);
        $availableItem->variants()->create(['inventory_id' => $availableInventory->id]);
        $group->featuredItems()->create(['catalog_item_id' => $availableItem->id]);

        $this->getJson("/api/tenants/{$tenant->codigo}/catalog")
            ->assertOk()
            ->assertJsonCount(1, '0.items')
            ->assertJsonPath('0.items.0.nombre', 'Available')
            ->assertJsonPath('0.items.0.unavailable_message', null)
            ->assertJsonMissing(['nombre' => 'Unavailable']);
    }

    public function test_column_with_image_uses_item_image_then_variant_image_then_null(): void
    {
        Storage::fake('s3');
        $tenant = $this->createTenant('catalog-images');
        $group = $this->createGroup($tenant, ProductLayout::ColumnWithImage, 'Images');

        $directItem = $this->createItem($tenant, 'Direct image');
        $directImage = $this->createAttachment('direct');
        $directItem->attachments()->attach($directImage, ['orden' => 0]);
        $group->featuredItems()->create([
            'catalog_item_id' => $directItem->id,
            'order' => 0,
        ]);

        $variantItem = $this->createItem($tenant, 'Variant image');
        $variantInventory = Inventory::query()->create();
        $variant = $variantItem->variants()->create(['inventory_id' => $variantInventory->id]);
        $variantImage = $this->createAttachment('variant');
        $variant->attachments()->attach($variantImage, ['orden' => 0]);
        $group->featuredItems()->create([
            'catalog_item_id' => $variantItem->id,
            'order' => 1,
        ]);

        $emptyItem = $this->createItem($tenant, 'No image');
        $group->featuredItems()->create([
            'catalog_item_id' => $emptyItem->id,
            'order' => 2,
        ]);

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

        $response
            ->assertOk()
            ->assertJsonPath('0.layout', ProductLayout::ColumnWithImage->value)
            ->assertJsonPath('0.items.data.0.nombre', 'Direct image')
            ->assertJsonPath('0.items.data.0.precio', '100.00')
            ->assertJsonPath('0.items.data.0.image', fn (?string $url): bool => str_contains($url ?? '', 'direct.png'))
            ->assertJsonPath('0.items.data.1.image', fn (?string $url): bool => str_contains($url ?? '', 'variant.png'))
            ->assertJsonPath('0.items.data.2.image', null);
    }

    public function test_index_always_returns_page_one_and_group_endpoint_returns_other_pages(): void
    {
        $tenant = $this->createTenant('catalog-pagination');
        $group = $this->createGroup($tenant, ProductLayout::Row, 'Paginated');

        foreach (range(1, 13) as $number) {
            $item = $this->createItem($tenant, "Item {$number}");
            $group->featuredItems()->create([
                'catalog_item_id' => $item->id,
                'order' => $number,
            ]);
        }

        $this->getJson("/api/tenants/{$tenant->codigo}/catalog?page=2")
            ->assertOk()
            ->assertJsonPath('0.items.meta.current_page', 1)
            ->assertJsonPath('0.items.meta.last_page', 2)
            ->assertJsonPath('0.items.meta.per_page', 12)
            ->assertJsonPath('0.items.meta.total', 13)
            ->assertJsonCount(12, '0.items.data')
            ->assertJsonPath('0.items.data.0.nombre', 'Item 1');

        $this->getJson(
            "/api/tenants/{$tenant->codigo}/catalog/featured-groups/{$group->id}/items?page=2"
        )
            ->assertOk()
            ->assertJsonPath('meta.current_page', 2)
            ->assertJsonPath('meta.last_page', 2)
            ->assertJsonCount(1, 'data')
            ->assertJsonPath('data.0.nombre', 'Item 13');
    }

    public function test_non_paginated_group_layouts_return_all_items_as_a_plain_array(): void
    {
        $tenant = $this->createTenant('catalog-simple-layouts');
        $layouts = [
            GroupLayout::Simple,
            GroupLayout::SimpleVertical,
            GroupLayout::Carousel,
        ];

        foreach ($layouts as $order => $groupLayout) {
            $group = $this->createGroup(
                $tenant,
                ProductLayout::Row,
                $groupLayout->value,
                $order,
                $groupLayout,
            );

            foreach (range(1, 13) as $number) {
                $item = $this->createItem($tenant, "{$groupLayout->value} Item {$number}");
                $group->featuredItems()->create([
                    'catalog_item_id' => $item->id,
                    'order' => $number,
                ]);
            }
        }

        $response = $this->getJson("/api/tenants/{$tenant->codigo}/catalog")->assertOk();
        $groups = $response->json();

        foreach ($layouts as $index => $groupLayout) {
            $this->assertSame($groupLayout->value, $groups[$index]['group_layout']);
            $this->assertCount(13, $groups[$index]['items']);
            $this->assertSame(
                "{$groupLayout->value} Item 1",
                $groups[$index]['items'][0]['nombre'],
            );
            $this->assertArrayNotHasKey('data', $groups[$index]['items']);
            $this->assertArrayNotHasKey('meta', $groups[$index]['items']);
        }

        $carouselGroup = FeaturedGroup::query()
            ->where('tenant_code', $tenant->codigo)
            ->where('group_layout', GroupLayout::Carousel)
            ->sole();

        $this->getJson(
            "/api/tenants/{$tenant->codigo}/catalog/featured-groups/{$carouselGroup->id}/items?page=2"
        )
            ->assertOk()
            ->assertJsonCount(13)
            ->assertJsonPath('0.nombre', 'carousel Item 1');
    }

    public function test_single_group_layout_returns_only_its_first_available_item(): void
    {
        $tenant = $this->createTenant('catalog-single-layout');
        $group = $this->createGroup(
            $tenant,
            ProductLayout::TicketSelector,
            'Entradas',
            groupLayout: GroupLayout::Single,
        );

        foreach (['Primera entrada', 'Segunda entrada'] as $order => $name) {
            $item = $this->createItem($tenant, $name);
            $group->featuredItems()->create([
                'catalog_item_id' => $item->id,
                'order' => $order,
            ]);
        }

        $this->getJson("/api/tenants/{$tenant->codigo}/catalog")
            ->assertOk()
            ->assertJsonPath('0.layout', ProductLayout::TicketSelector->value)
            ->assertJsonPath('0.group_layout', GroupLayout::Single->value)
            ->assertJsonCount(1, '0.items')
            ->assertJsonPath('0.items.0.nombre', 'Primera entrada')
            ->assertJsonMissingPath('0.items.0.variants');
    }

    public function test_groups_can_source_items_from_a_category_or_the_entire_catalog(): void
    {
        $tenant = $this->createTenant('catalog-sources');
        $category = Category::query()->create([
            'tenant_code' => $tenant->codigo,
            'nombre' => 'Food',
        ]);

        FeaturedGroup::query()->create([
            'tenant_code' => $tenant->codigo,
            'source_type' => FeaturedGroupSource::Category,
            'category_id' => $category->id,
            'product_layout' => ProductLayout::Row,
            'group_layout' => GroupLayout::Simple,
            'group_name' => 'Food',
            'group_order' => 0,
        ]);
        FeaturedGroup::query()->create([
            'tenant_code' => $tenant->codigo,
            'source_type' => FeaturedGroupSource::All,
            'product_layout' => ProductLayout::Row,
            'group_layout' => GroupLayout::Paginated,
            'group_name' => 'All products',
            'group_order' => 1,
        ]);

        $food = $this->createItem($tenant, 'Hamburger');
        $food->update(['group_order' => 2]);
        $food->category()->associate($category)->save();
        $parking = $this->createItem($tenant, 'Parking');
        $parking->update(['group_order' => 1]);

        $this->getJson("/api/tenants/{$tenant->codigo}/catalog")
            ->assertOk()
            ->assertJsonPath('0.title', 'Food')
            ->assertJsonCount(1, '0.items')
            ->assertJsonPath('0.items.0.nombre', 'Hamburger')
            ->assertJsonPath('1.title', 'All products')
            ->assertJsonCount(2, '1.items.data')
            ->assertJsonPath('1.items.data.0.nombre', 'Parking')
            ->assertJsonPath('1.items.data.1.nombre', 'Hamburger')
            ->assertJsonMissingPath('1.items.data.0.group_order')
            ->assertJsonPath('1.items.meta.total', 2);
    }

    public function test_index_excludes_items_from_disabled_categories(): void
    {
        $tenant = $this->createTenant('catalog-disabled-category');
        $group = $this->createGroup(
            $tenant,
            ProductLayout::Row,
            'All products',
            groupLayout: GroupLayout::Simple,
        );
        $enabledCategory = Category::query()->create([
            'tenant_code' => $tenant->codigo,
            'nombre' => 'Enabled',
        ]);
        $disabledCategory = Category::query()->create([
            'tenant_code' => $tenant->codigo,
            'nombre' => 'Disabled',
            'is_enabled' => false,
        ]);

        $enabledItem = $this->createItem($tenant, 'Enabled item');
        $enabledItem->category()->associate($enabledCategory)->save();
        $disabledItem = $this->createItem($tenant, 'Disabled item');
        $disabledItem->category()->associate($disabledCategory)->save();
        $uncategorizedItem = $this->createItem($tenant, 'Uncategorized item');

        foreach ([$enabledItem, $disabledItem, $uncategorizedItem] as $order => $item) {
            $group->featuredItems()->create([
                'catalog_item_id' => $item->id,
                'order' => $order,
            ]);
        }

        $this->getJson("/api/tenants/{$tenant->codigo}/catalog")
            ->assertOk()
            ->assertJsonCount(2, '0.items')
            ->assertJsonPath('0.items.0.nombre', 'Enabled item')
            ->assertJsonPath('0.items.1.nombre', 'Uncategorized item')
            ->assertJsonMissing(['nombre' => 'Disabled item']);

        $this->getJson(
            "/api/tenants/{$tenant->codigo}/catalog/featured-groups/{$group->id}/items"
        )
            ->assertOk()
            ->assertJsonCount(2)
            ->assertJsonMissing(['nombre' => 'Disabled item']);
    }

    private function createGroup(
        Tenant $tenant,
        ProductLayout $layout,
        string $name,
        int $order = 0,
        GroupLayout $groupLayout = GroupLayout::Paginated,
    ): FeaturedGroup {
        return FeaturedGroup::query()->create([
            'tenant_code' => $tenant->codigo,
            'product_layout' => $layout,
            'group_layout' => $groupLayout,
            'group_name' => $name,
            'group_order' => $order,
        ]);
    }

    private function createItem(
        Tenant $tenant,
        string $name,
        ?Inventory $inventory = null,
    ): 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,
        ]);
    }

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