<?php

namespace App\Http\Resources;

use Illuminate\Contracts\Pagination\LengthAwarePaginator;
use Illuminate\Http\Resources\Json\JsonResource;
use Mtc\VehicleValuation\Models\VehicleValuation;

class ValuationList extends JsonResource
{
    /**
     * Transform the resource into an array.
     *
     * @param  \Illuminate\Http\Request  $request
     * @return array|\Illuminate\Contracts\Support\Arrayable|\JsonSerializable
     */
    public function toArray($request)
    {
        if ($this->resource instanceof LengthAwarePaginator) {
            $this->resource
                ->through(fn(VehicleValuation $valuation) => $this->mapRecod($valuation));
        } else {
            $this->resource = $this->resource
                ->map(fn(VehicleValuation $valuation) => $this->mapRecod($valuation));
        }
        return parent::toArray($request);
    }
    /**
     * Convert vehicle to the json format used in lists
     *
     * @param VehicleValuation $valuation
     * @return array
     */
    protected function mapRecod(VehicleValuation $valuation)
    {
        return [
            'name' => $valuation->registration,
            'description' => $valuation->make . ' ' . $valuation->model,
            'metaItems' => [
                number_format($valuation->mileage),
                "&pound;" . number_format($valuation->retail_price),
                $valuation->created_at->format('d/m/Y H:i'),
            ],
            'link' => '/manage-content/valuations/view/' . $valuation->id,
            'id' => $valuation->id,
        ];
    }
}
