<?php

namespace App\Domains\Ticket\Services;

use App\Domains\Ticket\Models\Ticket;

class TicketPresentationResolver
{
    /** Relaciones necesarias para calcular nombre y descripción sin consultas N+1. */
    public const RELATIONS = [
        'sourceCatalogItem',
        'sourceVariant.catalogItem.itemAttributes.attribute.options',
        'sourceVariant.definitions.itemAttribute.attribute.options',
        'sourceVariant.eventDates',
        'sourceVariant.eventDate',
    ];

    public function name(Ticket $ticket): string
    {
        $ticket->loadMissing(self::RELATIONS);
        $catalogItem = $ticket->sourceCatalogItem;

        if ($catalogItem === null) {
            return '';
        }

        $variant = $ticket->sourceVariant;
        if ($variant === null) {
            return $catalogItem->nombre;
        }

        $itemAttributes = $variant->catalogItem->itemAttributes;
        $properties = $variant->selectionOptions($itemAttributes)
            ->map(function (array $option, string $attributeCode) use ($itemAttributes): ?string {
                $labels = collect(array_is_list($option) ? $option : [$option])
                    ->pluck('label')
                    ->filter(fn ($label): bool => is_string($label) && $label !== '')
                    ->implode(', ');

                if ($labels === '') {
                    return null;
                }

                $ticketLabel = $itemAttributes->first(
                    fn ($itemAttribute): bool => $itemAttribute->attribute?->codigo === $attributeCode,
                )?->ticket_label;

                return is_string($ticketLabel) && trim($ticketLabel) !== ''
                    ? trim($ticketLabel).' '.$labels
                    : $labels;
            })
            ->filter()
            ->values();

        return $properties->isEmpty()
            ? $catalogItem->nombre
            : $catalogItem->nombre.' ('.$properties->implode(', ').')';
    }

    public function description(Ticket $ticket): string
    {
        $ticket->loadMissing(self::RELATIONS);

        return (string) ($ticket->sourceVariant?->getDescription()
            ?? $ticket->sourceCatalogItem?->descripcion
            ?? '');
    }
}
