<?php

namespace App\Http\Resources;

use Mtc\ContentManager\Http\Resources\ContentCategoryListResource;
use Mtc\ContentManager\Models\ContentCategory;

class ContentCategoryList extends ContentCategoryListResource
{
    /**
     * 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 (ContentCategory $category) => $this->mapRecord($category));
        } else {
            $this->resource = $this->resource->map(fn (ContentCategory $category) => $this->mapRecord($category));
        }

        return parent::toArray($request);
    }

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