<?php

namespace App\Http\Resources;

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

class FormList extends JsonResource
{
    /**
     * Transform the resource into an array.
     *
     * @param Request $request
     * @return array
     */
    public function toArray($request)
    {
        if ($this->resource instanceof LengthAwarePaginator) {
            $resource = $this->resource
                ->through(fn(Form $form) => $this->mapRecord($form))
                ->toArray();

            $resource['default_columns'] = [
                'updated',
                'type',
            ];
            return $resource;
        }

        $this->resource = $this->resource
            ->map(fn(Form $form) => $this->mapRecord($form));
        return parent::toArray($request);
    }

    public function mapRecord(Form $form)
    {
        return [

            'id' => $form->id,
            'title' => $form->name,
            'link' => '/crm/forms/edit/' . $form->id,
            'metaItems' => [
                'updated' => $form->updated_at->diffForHumans(),
                'type' => $form->type?->name,
            ],
        ];
    }
}
