<?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
     */
    #[\Override]
    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) : [],
            'images' => $page->primaryMediaUse
                ? [
                    [
                        'id' => $page->primaryMediaUse->id,
                        'title' => $page->primaryMediaUse->title,
                        'alt_text' => $page->primaryMediaUse->alt_text,
                        'description' => $page->primaryMediaUse->description,
                        'caption' => $page->primaryMediaUse->caption,
                        'src' => $page->primaryMediaUse->media->getOriginalUrlAttribute(),
                        'sizes' => $this->allSizesForUse($page, $page->primaryMediaUse)
                            ->put('original', $page->primaryMediaUse->media->getOriginalUrlAttribute()),
                        'type' => $page->primaryMediaUse->media->type,
                        'interior' => $page->primaryMediaUse->interior,
                        'exterior' => $page->primaryMediaUse->exterior,
                        'hex1' => $page->primaryMediaUse->media?->hex1,
                        'hex2' => $page->primaryMediaUse->media?->hex2,
                    ]
                ]
                : null,
            'date' => $page->published_at?->format('F j, Y'),
            'tags' => $page->tags?->pluck('name', 'slug'),
            'categories' => $page->categories?->pluck('name', 'slug'),
            'excerpt' => $page->excerpt,
            'estimated_read_time' => $page->estimated_read_time,
        ];
    }

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