<?php
namespace QuizPress;

use QuizPress\Integration\LiteSpeedCache;

if ( ! defined( 'ABSPATH' ) ) {
    exit;
}

class Integration {
    public static function init() {
        self::add_cache_plugin_integration();
        self::exclude_rest_api_from_cache();
    }

    public static function add_cache_plugin_integration() {
        LiteSpeedCache::init();
    }

    /**
     * Keep cache plugins off the QuizPress REST API.
     *
     * The quizpress/* endpoints serve live, per-user quiz data
     * ( render_quiz, attempts, leaderboard, analytics … ). Page-cache
     * plugins such as LiteSpeed cache public GET responses, which serves
     * stale data and breaks quiz flows. The `wp` action used for page-level
     * exclusion never fires during a REST request, so exclude the namespace
     * from inside REST dispatch instead.
     *
     * @return void
     */
    public static function exclude_rest_api_from_cache() {
        add_filter( 'rest_pre_dispatch', [ __CLASS__, 'set_rest_nocache' ], 10, 3 );
    }

    /**
     * @param mixed            $result  Response to replace the requested version with.
     * @param \WP_REST_Server  $server  Server instance.
     * @param \WP_REST_Request $request Request used to generate the response.
     *
     * @return mixed Untouched $result.
     */
    public static function set_rest_nocache( $result, $server, $request ) {
        if ( strpos( $request->get_route(), '/' . QUIZPRESS_PLUGIN_SLUG . '/' ) === 0 ) {
            // Generic: W3TC / WP Rocket / WP Super Cache + browser caches.
            nocache_headers();
            // LiteSpeed-native control ( no-op when LiteSpeed is inactive ).
            do_action( 'litespeed_control_set_nocache', 'quizpress rest api' );
        }

        return $result;
    }
}