<?php

namespace App\Http\Resources;

use Illuminate\Http\Resources\Json\JsonResource;
use Illuminate\Pagination\LengthAwarePaginator;
use Mtc\ContentManager\Contracts\Template;

class TemplateListResource extends JsonResource
{
    /**
     * @var LengthAwarePaginator
     */
    public $resource;

    /**
     * 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 \Illuminate\Contracts\Pagination\LengthAwarePaginator) {
            $this->resource
                ->through(fn (Template $vehicle) => $this->mapRecord($vehicle));
        } else {
            $this->resource = $this->resource
                ->map(fn (Template $vehicle) => $this->mapRecord($vehicle));
        }
        return parent::toArray($request);
    }

    /**
     * Map template record
     *
     * @param Template $template
     * @return array
     */
    protected function mapRecord(Template $template)
    {
        return [
            'id' => $template->id,
            'title' => $template->name,
            'description' => $template->description ?? '',
            'image' => [
                'src' => null,
                'alt' => $template->title,
            ],
            'link' => '/manage-content/templates/edit/' . $template->id,
            'disallow_delete' => $template->meta['disallow_delete'] ?? false,
            'locked' => ($template->meta['locked'] ?? false) === true,
            'metaItems' => [
                $template->updated_at->diffForHumans(),
                $template->status,
                $template->updatedBy
                    ? [
                        'id' => $template->updatedBy->id,
                        'name' => $template->updatedBy->name,
                        'src' => $template->updatedBy->profile_photo_url,
                    ]
                    : null
            ],
        ];
    }
}
