<?php

declare(strict_types=1);

namespace App\Http\Resources;

use App\Models\BasicBasketProduct;
use App\Models\StoreProductTarget;
use Illuminate\Http\Request;
use Illuminate\Http\Resources\Json\JsonResource;
use Illuminate\Support\Carbon;
use Illuminate\Support\Collection;

/**
 * @mixin BasicBasketProduct
 */
class BasicBasketProductDetailResource extends JsonResource
{
    /**
     * @return array<string, mixed>
     */
    public function toArray(Request $request): array
    {
        /** @var Collection<int, StoreProductTarget> $targets */
        $targets = $this->resource->targets;

        /** @var Carbon|null $latestCheckedAt */
        $latestCheckedAt = $targets
            ->map(fn (StoreProductTarget $t): ?Carbon => $t->latestObservation?->observed_at)
            ->filter()
            ->sortDesc()
            ->first();

        return [
            'id' => $this->id,
            'slug' => $this->slug,
            'name' => $this->name,
            'category' => $this->category,
            'expected_unit' => $this->expected_unit,
            'image_url' => $this->image_url !== null ? url($this->image_url) : null,
            'latest_checked_at' => $latestCheckedAt,
            'stores' => StorePriceResource::collection($targets),
        ];
    }
}
