<?php

namespace App\Domains\Catalog\Resources;

use App\Domains\Catalog\Enums\InventoryPolicy;
use App\Domains\Catalog\Enums\ProductLayout;
use App\Domains\Catalog\Models\CatalogItem;
use App\Domains\Catalog\Models\FeaturedGroup;
use App\Domains\Catalog\Models\Variant;
use App\Domains\Catalog\Services\CatalogItemAllowanceService;
use Illuminate\Http\Request;
use Illuminate\Http\Resources\Json\JsonResource;

/** @mixin CatalogItem */
class CatalogFeaturedItemResource extends JsonResource
{
    /** @return array<string, mixed> */
    public function toArray(Request $request): array
    {
        $catalogItem = $this->resource;
        /** @var FeaturedGroup $featuredGroup */
        $featuredGroup = $catalogItem->getRelation('featuredGroup');

        if ($featuredGroup->product_layout === ProductLayout::ColumnWithImage) {
            return $this->columnWithImageData($catalogItem);
        }

        if ($featuredGroup->product_layout === ProductLayout::TicketSelector) {
            return $this->ticketSelectorData($catalogItem);
        }

        $remainingUserQuota = $catalogItem->getAttribute('remaining_user_quota');
        $availableStock = $catalogItem->availableStock();

        $data = [
            'id' => $catalogItem->id,
            'type' => $catalogItem->type->value,
            'nombre' => $catalogItem->nombre,
            'descripcion' => $catalogItem->descripcion,
            'precio' => $catalogItem->precio,
            'maximum_addable_quantity' => $this->maximumAddable(
                $availableStock,
                $remainingUserQuota,
            ),
            'unavailable_message' => $this->unavailableMessage(
                $availableStock,
                $remainingUserQuota,
            ),
            'variants' => $catalogItem->visibleVariants()
                ->map(function (Variant $variant) use ($catalogItem, $remainingUserQuota): array {
                    $variantStock = $catalogItem->inventory_policy === InventoryPolicy::Unlimited
                        ? null
                        : $variant->inventory->availableStock();

                    return [
                        'id' => $variant->id,
                        'event_date_id' => $variant->event_date_id,
                        'event_date' => $variant->eventDate?->date?->format('Y-m-d'),
                        'event_date_ids' => $variant->selectedEventDates()->pluck('id')->values(),
                        'event_dates' => $variant->selectedEventDates()->map(fn ($eventDate): string => $eventDate->date->format('Y-m-d'))->values(),
                        'descripcion' => $variant->getDescription(),
                        'precio' => number_format($variant->getPrice(), 2, '.', ''),
                        'maximum_addable_quantity' => $this->maximumAddable(
                            $variantStock,
                            $remainingUserQuota,
                        ),
                        'unavailable_message' => $this->unavailableMessage(
                            $variantStock,
                            $remainingUserQuota,
                        ),
                        'values' => $variant->selectorOptions($catalogItem->itemAttributes),
                    ];
                })
                ->values(),
        ];

        return $data;
    }

    /** @return array<string, mixed> */
    private function ticketSelectorData(CatalogItem $catalogItem): array
    {
        $availableStock = $catalogItem->availableStock();
        $remainingUserQuota = $catalogItem->getAttribute('remaining_user_quota');

        return [
            'id' => $catalogItem->id,
            'type' => $catalogItem->type->value,
            'nombre' => $catalogItem->nombre,
            'descripcion' => $catalogItem->descripcion,
            'precio' => $catalogItem->precio,
            'image' => $this->firstImageUrl($catalogItem),
            'maximum_addable_quantity' => $this->maximumAddable($availableStock, $remainingUserQuota),
            'unavailable_message' => $this->unavailableMessage($availableStock, $remainingUserQuota),
        ];
    }

    /** @return array<string, mixed> */
    private function columnWithImageData(CatalogItem $catalogItem): array
    {
        $availableStock = $catalogItem->availableStock();
        $remainingUserQuota = $catalogItem->getAttribute('remaining_user_quota');

        return [
            'id' => $catalogItem->id,
            'type' => $catalogItem->type->value,
            'nombre' => $catalogItem->nombre,
            'precio' => $catalogItem->precio,
            'image' => $this->firstImageUrl($catalogItem),
            'maximum_addable_quantity' => $this->maximumAddable($availableStock, $remainingUserQuota),
            'unavailable_message' => $this->unavailableMessage($availableStock, $remainingUserQuota),
        ];
    }

    private function firstImageUrl(CatalogItem $catalogItem): ?string
    {
        $attachment = $catalogItem->attachments->first()
            ?? $catalogItem->visibleVariants()
                ->flatMap(fn (Variant $variant) => $variant->attachments)
                ->first();

        return $attachment?->getTemporaryUrl(1440);
    }

    private function maximumAddable(?int $stock, ?int $remainingUserQuota): ?int
    {
        return app(CatalogItemAllowanceService::class)
            ->maximumAddableQuantity($stock, $remainingUserQuota);
    }

    private function unavailableMessage(?int $stock, ?int $remainingUserQuota): ?string
    {
        return app(CatalogItemAllowanceService::class)
            ->unavailableMessage($stock, $remainingUserQuota);
    }
}
