<?php

declare(strict_types=1);

/*
 * This file is part of the TYPO3 CMS project.
 *
 * It is free software; you can redistribute it and/or modify it under
 * the terms of the GNU General Public License, either version 2
 * of the License, or any later version.
 *
 * For the full copyright and license information, please read the
 * LICENSE.txt file that was distributed with this source code.
 *
 * The TYPO3 project - inspiring people to share!
 */

namespace TYPO3\CMS\Backend\Security\ContentSecurityPolicy;

use Psr\Http\Message\ResponseInterface;
use Psr\Http\Message\ServerRequestInterface;
use TYPO3\CMS\Backend\Attribute\AsController;
use TYPO3\CMS\Backend\Module\ModuleInterface;
use TYPO3\CMS\Backend\Routing\UriBuilder;
use TYPO3\CMS\Backend\Template\Components\ButtonBar;
use TYPO3\CMS\Backend\Template\Components\ComponentFactory;
use TYPO3\CMS\Backend\Template\ModuleTemplate;
use TYPO3\CMS\Backend\Template\ModuleTemplateFactory;
use TYPO3\CMS\Core\Authentication\BackendUserAuthentication;
use TYPO3\CMS\Core\Configuration\Features;
use TYPO3\CMS\Core\Imaging\IconFactory;
use TYPO3\CMS\Core\Localization\LanguageService;
use TYPO3\CMS\Core\Page\PageRenderer;
use TYPO3\CMS\Core\Security\ContentSecurityPolicy\ScopeRepository;
use TYPO3\CMS\Core\Utility\ExtensionManagementUtility;

/**
 * Content-Security-Policy backend module view, loading the CSP lit-element and providing the current context.
 * @internal This is a specific Backend Controller implementation and is not considered part of the Public TYPO3 API.
 */
#[AsController]
readonly class CspModuleController
{
    public function __construct(
        protected Features $features,
        protected UriBuilder $uriBuilder,
        protected PageRenderer $pageRenderer,
        protected ScopeRepository $scopeRepository,
        protected ModuleTemplateFactory $moduleTemplateFactory,
        protected IconFactory $iconFactory,
        protected ComponentFactory $componentFactory,
    ) {}

    public function mainAction(ServerRequestInterface $request): ResponseInterface
    {
        $view = $this->moduleTemplateFactory->create($request);
        $this->registerDocHeaderButtons($view, $request->getAttribute('module'));
        $view->assignMultiple([
            'configurationStatus' => $this->getConfigurationStatus(),
            'scopes' => array_map(strval(...), $this->scopeRepository->findAll()),
            'controlUri' => $this->uriBuilder->buildUriFromRoutePath('/ajax/security/csp/control'),
            'extLowlevelAvailable' => ExtensionManagementUtility::isLoaded('lowlevel'),
        ]);
        return $view->renderResponse('Security/CspModule');
    }

    protected function registerDocHeaderButtons(ModuleTemplate $view, ModuleInterface $currentModule): void
    {
        $view->getDocHeaderComponent()->setShortcutContext(
            $currentModule->getIdentifier(),
            $this->getLanguageService()->translate('title', 'backend.modules.content_security_policy')
        );
        $view->getDocHeaderComponent()->disableAutomaticReloadButton();
        $reloadButton = $this->componentFactory
            ->createReloadButton((string)$this->uriBuilder->buildUriFromRoute($currentModule->getIdentifier()))
            ->setDataAttributes(['csp-reports-handler' => 'refresh']);
        $view->addButtonToButtonBar($reloadButton, ButtonBar::BUTTON_POSITION_RIGHT);
    }

    protected function getConfigurationStatus(): array
    {
        return [
            'featureDisabled' => array_filter([
                'backend' => [],
                'frontend' => !$this->features->isFeatureEnabled('security.frontend.enforceContentSecurityPolicy')
                    && !$this->features->isFeatureEnabled('security.frontend.reportContentSecurityPolicy')
                        ? ['enforce', 'report']
                        : [],
            ]),
            'customReporting' => array_filter([
                'BE' => $GLOBALS['TYPO3_CONF_VARS']['BE']['contentSecurityPolicyReportingUrl'] ?? '',
                'FE' => $GLOBALS['TYPO3_CONF_VARS']['FE']['contentSecurityPolicyReportingUrl'] ?? '',
            ]),
        ];
    }

    protected function getBackendUser(): BackendUserAuthentication
    {
        return $GLOBALS['BE_USER'];
    }

    protected function getLanguageService(): LanguageService
    {
        return $GLOBALS['LANG'];
    }
}
