<?php

namespace App\Domains\Sale\Resources\AdminApp;

use App\Domains\Purchase\Models\Purchase;
use App\Domains\Purchase\Models\PurchaseItem;
use Illuminate\Http\Request;
use Illuminate\Http\Resources\Json\JsonResource;

/** @mixin Purchase */
class SaleDetailResource extends JsonResource
{
    /** @return array<string, mixed> */
    public function toArray(Request $request): array
    {
        return [
            'id' => $this->id,
            'items' => $this->items->map(fn (PurchaseItem $item): array => [
                'id' => $item->id,
                'product' => $item->item_nombre,
                'event_dates' => $this->eventDates($item),
                'quantity' => (int) $item->cantidad,
                'unit_price' => $this->formatMoney($item->precio_unitario),
                'total' => $this->formatMoney($item->total),
            ])->values(),
            'total' => $this->formatMoney($this->total),
        ];
    }

    /** @return list<string> */
    private function eventDates(PurchaseItem $item): array
    {
        return collect($item->variant_attributes ?? [])
            ->filter(fn (mixed $attribute): bool => is_array($attribute)
                && mb_strtolower(trim((string) ($attribute['name'] ?? ''))) === 'fecha')
            ->flatMap(function (array $attribute): array {
                $value = $attribute['value'] ?? [];

                return is_array($value) ? $value : [$value];
            })
            ->filter(fn (mixed $date): bool => is_string($date) && $date !== '')
            ->values()
            ->all();
    }

    private function formatMoney(float|int|string|null $amount): string
    {
        return number_format((float) ($amount ?? 0), 2, '.', '');
    }
}
