<?php

namespace App\Http\Resources;

use Illuminate\Contracts\Pagination\LengthAwarePaginator;
use Illuminate\Http\Resources\Json\JsonResource;
use Illuminate\Support\Collection;
use Mtc\ContentManager\Contracts\VersionModel;

class VersionListResource extends JsonResource
{
    /**
     * @var LengthAwarePaginator|Collection
     */
    public $resource;

    /**
     * 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 (VersionModel $version) => $this->map($version));
            $data = $this->resource->toArray();
            $data['filters'] = [
                [
                    'name' => 'Pending Review',
                    'value' => 'pending-review',
                ],
                [
                    'name' => 'Changes Requested',
                    'value' => 'changes-requested',
                ],
            ];
            return $data;
        }
        $this->resource = $this->resource->map(fn (VersionModel $version) => $this->map($version));

        return parent::toArray($request);
    }

    /**
     * Map page entry
     *
     * @param VersionModel $version
     * @return array
     */
    private function map(VersionModel $version)
    {
        return [
            'id' => $version->id,
            'title' => $version->id . ' - ' . $version->page->title . ' by ' . $version->author->name,
            'description' => $version->page->title,
            'image' => [
                'src' => $version->page->primaryMediaUse?->getUrl('mini-thumb'),
                'alt' => $version->title,
            ],
            'link' => '/manage-content/content/edit/' . $version->page_id . '/version/' . $version->id,
            'metaItems' => [
                $version->status,
                $version->updated_at->diffForHumans(),
                [
                    'alt' => $version->author->name,
                    'src' => $version->author->profile_photo_url
                ]
            ],
        ];
    }
}
