<?php

namespace App\Domains\Catalog\Resources;

use App\Domains\Catalog\Enums\InventoryPolicy;
use App\Domains\Catalog\Models\CatalogItem;
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 CatalogSearchItemResource extends JsonResource
{
    /** @return array<string, mixed> */
    public function toArray(Request $request): array
    {
        $availableStock = $this->availableStock();
        $visibleVariants = $this->visibleVariants();
        $attachment = $this->attachments->first()
            ?? $visibleVariants
                ->flatMap(fn (Variant $variant) => $variant->attachments)
                ->first();

        return [
            'id' => $this->id,
            'type' => $this->type->value,
            'nombre' => $this->nombre,
            'descripcion' => $this->descripcion,
            'precio' => $this->precio,
            'image' => $attachment?->getTemporaryUrl(1440),
            'maximum_addable_quantity' => $this->maximumAddable($availableStock),
            'unavailable_message' => $this->unavailableMessage($availableStock),
            'variants' => $visibleVariants
                ->map(function (Variant $variant): array {
                    $variantStock = $this->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),
                        'unavailable_message' => $this->unavailableMessage($variantStock),
                        'values' => $variant->selectorOptions($this->itemAttributes),
                    ];
                })
                ->values(),
        ];
    }

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

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