<?php

namespace App\Http\Resources;

use Mtc\ContentManager\Http\Resources\ContentTagListResource;
use Mtc\ContentManager\Models\ContentTag;

class ContentTagList extends ContentTagListResource
{
    /**
     * 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 \Illuminate\Contracts\Pagination\LengthAwarePaginator) {
            $this->resource->through(fn(ContentTag $tag) => $this->mapRecord($tag));
        } else {
            $this->resource = $this->resource->map(fn(ContentTag $tag) => $this->mapRecord($tag));
        }

        return parent::toArray($request);
    }

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