<?php

namespace App\Domains\Desfile\Resources;

use App\Domains\Catalog\Models\CatalogItem;
use Illuminate\Http\Request;
use Illuminate\Http\Resources\Json\JsonResource;

/** @mixin CatalogItem */
class EntryResource extends JsonResource
{
    /** @return array<string, mixed> */
    public function toArray(Request $request): array
    {
        $image = $this->allAttachments->first();

        return [
            'id' => $this->id,
            'rows' => $this->variants
                ->map(function ($variant): array {
                    $values = $variant->selectionValues();

                    return [
                        'type' => $values->get('tipo'),
                        'sector' => $values->get('sector'),
                        'row' => $values->get('fila'),
                        'seat' => (int) $values->get('asiento'),
                        'price' => $variant->getPrice(),
                    ];
                })
                ->groupBy(fn (array $variant): string => implode('|', [
                    mb_strtolower(trim((string) $variant['type'])),
                    mb_strtolower(trim((string) $variant['sector'])),
                    mb_strtolower(trim((string) $variant['row'])),
                ]))
                ->map(function ($variants): array {
                    $first = $variants->first();

                    return [
                        'type' => $first['type'],
                        'sector' => $first['sector'],
                        'row' => $first['row'],
                        'max_seat' => $variants->max('seat'),
                        'price' => number_format($first['price'], 2, '.', ''),
                    ];
                })
                ->values(),
            'image' => $image === null ? null : [
                'key' => $image->key,
                'filename' => $image->filename,
                'url' => $image->getTemporaryUrl(1440),
                'is_enabled' => (bool) $image->pivot->is_enabled,
            ],
        ];
    }
}
