<?php

namespace App\Http\Resources;

use App\Traits\MediaHasSizes;
use Illuminate\Contracts\Pagination\LengthAwarePaginator;
use Illuminate\Http\Resources\Json\JsonResource;

class PageListResource extends JsonResource
{
    use MediaHasSizes;

    /**
     * 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 LengthAwarePaginator) {
            $this->resource
                ->through(fn ($page) => $this->mapPage($page));
        } else {
            $this->resource = $this->resource
                ->map(fn($page) => $this->mapPage($page));
        }

        return parent::toArray($request);
    }

    public function mapPage($page): array
    {
        return [
            'url' => $this->getPageUrl($page),
            'title' => $page->title,
            'thumbnail' => $page->primaryMediaUse?->getUrl('square-tile'),
            'image' => $page->primaryMediaUse ? $this->allSizesForUse($page, $page->primaryMediaUse) : [],
            'date' => $page->published_at?->format('F j, Y'),
            'tags' => $page->tags?->pluck('name', 'slug'),
            'categories' => $page->categories?->pluck('name', 'slug'),
            'excerpt' => $page->excerpt,
        ];
    }

    private function getPageUrl($page): string
    {
        return '/' . collect([
                $page->category,
                $page->slug
            ])->filter()
            ->implode('/');
    }
}
