<?php

namespace WordpressModels\Page;

use Symfony\Component\HttpFoundation\Request;
use WordpressModels\DependencyInjection\HookAttributes\Attributes\AjaxAction;
use WordpressModels\DependencyInjection\Pages\PageRegistry;

/**
 * Class AsyncPageDataFetch
 *
 * Service to fetch page data asynchronously.
 *
 * Pages registered to the PageRegistry are used to build the context.
 */
class AsyncPageData
{

    public const NONCE_ID = 'wpm_load_page_data_nonce';

    public function __construct(private PageRegistry $pageRegistry)
    {
    }

    /**
     * Load the data for a page asynchronously.
     *
     * This method is meant to be used in client-side admin pages to fetch data asynchronously and to check permissions.
     * If the request returns a 403 Forbidden status, the client-side application should deny the user access to the
     * page.
     *
     * This action is protected by a nonce, which is automatically generated by the {@see AbstractPage} class and
     * injected into the 'page' javascript object.
     *
     * @param Request $request
     * @return array
     * @throws \HttpException
     */
    #[AjaxAction('wpm_load_page_data', nonceId: self::NONCE_ID)]
    public function loadPageData(Request $request): array
    {
        $pageId = $request->get('page');
        $data = [];
        if ($page = $this->pageRegistry->getPage($pageId)) {
            if (!current_user_can($page->getCapability())) {
                throw new \HttpException('Unauthorized', \WP_Http::FORBIDDEN);
            }

            $params = $request->get('params', []);
            $data = [
                ...$page->buildContext($params),
                'permission' => $page->getCapability()
            ];

        }
        return $data;
    }

}
