<?php

namespace App\Http\Resources;

use Illuminate\Contracts\Pagination\LengthAwarePaginator;
use Illuminate\Http\Resources\Json\JsonResource;
use Mtc\MercuryDataModels\KeyloopLeaseVehicleVariant;

class LeaseVariantListResource 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(KeyloopLeaseVehicleVariant $vehicle) => $this->mapVehicle($vehicle));
        } else {
            $this->resource = $this->resource
                ->map(fn(KeyloopLeaseVehicleVariant $vehicle) => $this->mapVehicle($vehicle));
            return parent::toArray($request);
        }

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

    /**
     * @param KeyloopLeaseVehicleVariant $vehicle
     * @return void
     */
    protected function mapVehicle(KeyloopLeaseVehicleVariant $vehicle)
    {
        return [
            'make' => $vehicle->make?->name,
            'model' => $vehicle->model?->name,
            'derivative' => $vehicle->derivative,
            'featured' => $vehicle->featured,
        ];
    }
}
