<?php

namespace App\Http\Resources;

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

class FranchiseList extends JsonResource
{
    public static $wrap = '';

    /**
     * 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(Franchise $vehicle) => $this->mapFranchise($vehicle));
        } else {
            $this->resource = $this->resource
                ->map(fn(Franchise $vehicle) => $this->mapFranchise($vehicle));
        }
        return parent::toArray($request);
    }

    /**
     * Convert franchise to list data
     *
     * @param Franchise $franchise
     * @return array
     */
    protected function mapFranchise(Franchise $franchise)
    {
        return [
            'id' => $franchise->id,
            'title' => $franchise->name,
            'metaItems' => [
                $franchise->make?->name
            ],
        ];
    }
}
