<?php

namespace App\Http\Resources;

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

class OfferTypeList 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 (OfferType $vehicle) => $this->mapRecord($vehicle));
        } else {
            $this->resource = $this->resource
                ->map(fn (OfferType $vehicle) => $this->mapRecord($vehicle));
        }
        $resource = $this->resource->toArray();
        $resource['view_columns'] = [
            [
                'id' => 'parent',
                'name' => 'Parent',
            ],
            [
                'id' => 'slug',
                'name' => 'Slug',
            ],
        ];
        $resource['default_columns'] = [
            'parent',
            'slug',
        ];
        return $resource;
    }

    /**
     * Convert vehicle to the json format used in lists
     *
     * @param OfferType $offerType
     * @return array
     */
    protected function mapRecord(OfferType $offerType)
    {
        return [
            'title' => $offerType->name,
            'metaItems' => [
                'parent' => $offerType->parent?->name,
                'slug' => $offerType->slug,
            ],
            'link' => '/manage-content/offer-types/edit/' . $offerType->id,
            'id' => $offerType->id,
        ];
    }
}
