<?php

namespace App\Http\Resources;

use Illuminate\Contracts\Pagination\LengthAwarePaginator;
use Mtc\ContentManager\Http\Resources\ContentElementList as BaseContentElementList;

class ContentElementList extends BaseContentElementList
{
    /**
     * 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($element) => $this->mapRecord($element));
            $resource = $this->resource->toArray();

            $resource['default_columns'] = [
                'component',
                'category',
            ];
            return $resource;
        }

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

    protected function mapRecord($element)
    {
        return [
            'id' => $element->id,
            'title' => $element->title,
            'description' => collect([
                $element->slug,
                $element->subtitle,
            ])->filter()->implode(' | '),
            'metaItems' => [
                'component' => $element->ui_component,
                'category' => $this->categoryName($element->category),
            ]
        ];
    }

    private function categoryName($elementCategory)
    {
        return collect(config('pages.block_categories', []))
            ->filter(fn ($category) => $category['id'] === $elementCategory)
            ->first()['name'] ?? '';
    }
}
