<?php

namespace App\Http\Resources;

use Illuminate\Http\Resources\Json\JsonResource;
use Illuminate\Pagination\LengthAwarePaginator;
use Illuminate\Support\Facades\Auth;
use Mtc\ContentManager\Traits\MapContentTrait;
use Mtc\MercuryDataModels\ContentElement;
use Mtc\MercuryDataModels\GlobalContent;

class VersionViewResource extends JsonResource
{
    use MapContentTrait;

    public static $wrap = '';

    /**
     * @var LengthAwarePaginator
     */
    public $resource;

    /**
     * Transform the resource into an array.
     *
     * @param \Illuminate\Http\Request $request
     * @return array|\Illuminate\Contracts\Support\Arrayable|\JsonSerializable
     */
    public function toArray($request)
    {
        $this->resource->load([
            'page.template',
            'content.mediaUses.media',
            'content.subContent.mediaUses.media',
            'content.subContent.subContent.mediaUses.media',
            'content.subContent.subContent.subContent.mediaUses.media',
            'content.globalContent.contentElement.fields',
            'content.contentElement.fields',
            'content.subContent.contentElement.fields',
            'content.subContent.subContent.contentElement.fields',
            'content.subContent.subContent.subContent.contentElement.fields',
        ]);

        $resource = $this->resource->toArray();

        $resource['author_name'] = $this->resource->author?->name;

        $resource['user_can_save'] = $this->userCanSaveResource();
        $resource['user_can_publish'] = $this->userCanPublishResource();
        $resource['has_flexible_template'] = $this->resource->page->template->meta['flexible'] ?? false;

        unset($resource['page']['text']);
        $resource['pageTitle'] = 'Version ' . $resource['id'] . ' | ' . $this->resource->page->title;
        $resource['content'] = $this->resource->content->map(fn ($content) => $this->mapContent($content));

        $blockResource = config('pages.content_element_block_resource');
        $elements = ContentElement::query()
            ->with('fields.childElement.fields.childElement.fields.childElement.fields')
            ->where('is_enabled', 1)
            ->where('drag_and_drop', 1)
            ->paginate(10);
        $page = $resource['page'];
        unset($resource['page']);
        return [
            'page' => $page,
            'version' => $resource,
            'global_content' => new $blockResource(GlobalContent::query()->paginate(10)),
            'elements' => new $blockResource($elements),
        ];
    }

    private function userCanSaveResource(): bool
    {
        return Auth::id() === $this->resource->author_id;
    }

    private function userCanPublishResource(): bool
    {
        return Auth::user()->hasPermissionTo('publish-content');
        // TODO: Further implementation of per-page restrictions on editor rights
    }
}
