<?php

namespace App\Http\Resources;

use App\Facades\Settings;
use App\Facades\Site;
use Illuminate\Support\Facades\Auth;
use Mtc\ContentManager\Http\Resources\PageViewResource as BasePageViewResource;
use Mtc\MercuryDataModels\SeoData;
use Mtc\MercuryDataModels\User;

class PageViewResource extends BasePageViewResource
{
    #[\Override]
    public function toArray($request)
    {
        $this->resource->password_protected = !empty($this->resource->password);
        $this->resource->seo = $this->getSeo();
        $this->resource->makeVisible([
            'password',
            'slug',
        ]);

        $this->resource->site_url = Site::pageUrl($this->resource, true);
        $resource =  parent::toArray($request);
        $resource['types'] = $this->getPageTypes();
        $resource['authors'] = $this->getAuthors();
        return $resource;
    }

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


    private function getSeo()
    {
        return SeoData::query()
            ->where('path', $this->resource->urlPath())->first();
    }

    private function getPageTypes()
    {
        return collect(config('pages.page_types'))
            ->filter(fn ($type) => Settings::get($type['config_key']))
            ->map(fn ($type) => [
                'id' => $type['value'],
                'name' => __('pages.types.' . $type['value']),
            ])
            ->prepend(['id' => null, 'name' => __('pages.types.content_page')])
            ->values()
            ->toArray();
    }

    private function getAuthors()
    {
        return tenant()->users()
            ->select(['users.id', 'users.name'])
            ->get()
            ->filter(fn(User $user) => $user->hasPermissionTo('create-content'))
            ->map(fn(User $user) => [
                'id' => $user->id,
                'name' => $user->name,
            ])
            ->values();
    }
}
