<?php
/**
 * @author Carsten Rose <carsten.rose@math.uzh.ch>
 */
defined('TYPO3') or die('Access denied.');

(static function () {

    \TYPO3\CMS\Extbase\Utility\ExtensionUtility::configurePlugin(
        'qfq',
        'Qfq',
        [\IMATHUZH\Qfq\Controller\QfqController::class => 'show'],
        [\IMATHUZH\Qfq\Controller\QfqController::class => 'show'],
        \TYPO3\CMS\Extbase\Utility\ExtensionUtility::PLUGIN_TYPE_CONTENT_ELEMENT
    );
    // Note: Page TSconfig lives in Configuration/page.tsconfig which TYPO3
    // v12+ auto-loads; the former addPageTSConfig() call was removed in v14.

    // Define how the qfq_qfq CType is rendered. Using addTypoScriptSetup()
    // writes directly into TYPO3_CONF_VARS.FE.defaultTypoScript_setup so
    // the rendering is available on every page without the site template
    // having to include anything explicitly. Previously this was
    // addTypoScript(..., 'defaultContentRendering') which only kicked in
    // when fluid_styled_content or a compatible site package
    // (e.g. UZH CD Template) pulled it into its rendering chain - in a
    // minimal v14 install without such a wrapper the CType had no
    // rendering definition.
    //
    // USER_INT (uncached) is the correct default for QFQ since output
    // depends on user session, SIP tokens and form state.
    \TYPO3\CMS\Core\Utility\ExtensionManagementUtility::addTypoScriptSetup('
tt_content.qfq_qfq = USER_INT
tt_content.qfq_qfq {
    userFunc = TYPO3\CMS\Extbase\Core\Bootstrap->run
    extensionName = Qfq
    pluginName = Qfq
}
');

    // Register a small backend stylesheet. Currently used to make the
    // Extension Manager configuration tabs wrap onto multiple lines
    // again (v14 default is horizontal scroll). See Backend.css.
    $GLOBALS['TYPO3_CONF_VARS']['BE']['stylesheets']['qfq']
        = 'EXT:qfq/Resources/Public/Css/Backend.css';

    // Relax TYPO3's strict cHash validation for QFQ pages.
    //
    // QFQ links can carry arbitrary user-defined GET parameters derived
    // from Form and Report configurations (field names, custom URL
    // params, dynamically added typeahead values, etc.). Any static
    // whitelist would miss installation-specific parameters, and QFQ
    // cannot generate a valid cHash for its SIP-protected links because
    // the URLs are built at request time with runtime state.
    //
    // Setting enforceValidation = false makes TYPO3 no longer return
    // 404 "Request parameters could not be validated (&cHash empty)"
    // when an unknown parameter arrives without a cHash. QFQ content
    // is rendered via USER_INT (uncached), so relaxing this does not
    // open the site to cache-poisoning via crafted URLs.
    $GLOBALS['TYPO3_CONF_VARS']['FE']['cacheHash']['enforceValidation'] = false;

    // Keep the known-QFQ-parameter whitelist for cache-key stability:
    // without these, each distinct SIP token / record id would create
    // a separate cache entry even though the underlying page HTML is
    // identical for all of them (the QFQ plugin runs in USER_INT and
    // reads the parameters itself).
    $qfqCHashExcluded = [
        's',                      // SIP token (CLIENT_SIP)
        'sip',                    // alternative SIP name
        'r',                      // record id (CLIENT_RECORD_ID)
        'recordId',               // alternative record id name
        'form',                   // form name (CLIENT_FORM)
        'action',                 // form/report action
        'urlparam',               // additional URL parameters blob
        'preventBuildDevPanel',   // suppresses the dev panel in the rendered page
        'qfqauthuser',            // AuthenticationService user SIP
        'qfqauthconf',            // AuthenticationService config SIP
    ];
    $existing = $GLOBALS['TYPO3_CONF_VARS']['FE']['cacheHash']['excludedParameters'] ?? [];
    $GLOBALS['TYPO3_CONF_VARS']['FE']['cacheHash']['excludedParameters'] = array_values(
        array_unique(array_merge(is_array($existing) ? $existing : [], $qfqCHashExcluded))
    );

    // Read the extension configuration directly from $GLOBALS. TYPO3 v14
    // forbids instantiating ExtensionConfiguration (or any service that
    // pulls CacheManager) during ext_localconf.php bootstrap.
    $extensionConfig = $GLOBALS['TYPO3_CONF_VARS']['EXTENSIONS']['qfq'] ?? [];

    if (!empty($extensionConfig['authEnable'])) {
        \TYPO3\CMS\Core\Utility\ExtensionManagementUtility::addService(
            'qfq',
            'auth' /* sv type */,
            'tx_qfq_auth' /* sv key */,
            [
                'title' => 'Authentication service',
                'description' => 'Authentication with Qfq',
                'subtype' => 'getUserFE,authUserFE',
                'available' => true,
                'priority' => intval($extensionConfig['authPriority']),
                'quality' => intval($extensionConfig['authQuality']),
                'os' => '',
                'exec' => '',
                'className' => \IMATHUZH\Qfq\Core\Typo3\QfqAuthenticationService::class,
            ]
        );
    }


})();
