<?php

namespace App\Http\Resources;

use App\Traits\FormatAsCurrency;
use Illuminate\Contracts\Pagination\LengthAwarePaginator;
use Illuminate\Http\Resources\Json\JsonResource;
use Mtc\MercuryDataModels\VehicleOffer;

class OfferTileListResource extends JsonResource
{
    use FormatAsCurrency;


    /**
     * Set the dimensions of thumbs
     *
     * @param string $dimensions
     * @return self
     */
    public function setThumbDimensions(string $dimensions): self
    {
        $this->thumbDimensions = $dimensions;
        return $this;
    }

    /**
     * Transform the resource into an array.
     *
     * @param  \Illuminate\Http\Request  $request
     * @return array|\Illuminate\Contracts\Support\Arrayable|\JsonSerializable
     */
    #[\Override]
    public function toArray($request)
    {
        if ($this->resource instanceof LengthAwarePaginator) {
            $this->resource->through(fn(VehicleOffer $offer) => $this->mapOffer($offer));

            return $this->resource->toArray();
        }

        $this->resource = $this->resource->map(fn(VehicleOffer $offer) => $this->mapOffer($offer));

        return parent::toArray($request);
    }

    /**
     * Convert vehicle to the json format used in lists
     *
     * @param VehicleOffer $offer
     * @return array
     */
    protected function mapOffer(VehicleOffer $offer)
    {
        return [
            'image' => [
                'src' => $offer->getPreviewImage('thumb'),
                'alt' => $offer->name,
            ],
            'title' => $offer->name,
            'description' => $offer->derivative,
            'price' => $this->asCurrency($offer->price ?? 0, tenant()->currency),
            'id' => $offer->id,
        ];
    }
}
