<?php
if (!defined('ABSPATH')) exit;

class WPTA_REST {
    public function __construct() {
        add_action('rest_api_init', array($this, 'routes'));
    }

    public function routes() {
        register_rest_route('wpta/v1', '/run', array(
            'methods' => 'POST',
            'callback' => array($this, 'run_audit'),
            'permission_callback' => function () { return current_user_can('manage_options'); }
        ));
        register_rest_route('wpta/v1', '/latest', array(
            'methods' => 'GET',
            'callback' => array($this, 'latest'),
            'permission_callback' => function () { return current_user_can('manage_options'); }
        ));
    }

    public function run_audit($request) {
        $limit = absint($request->get_param('limit')) ?: 25;
        $engine = new WPTA_Audit_Engine();
        return rest_ensure_response($engine->run(array('limit' => $limit, 'mode' => 'manual')));
    }

    public function latest() {
        $run = WPTA_Utils::last_run();
        if (!$run) return rest_ensure_response(array('run' => null, 'issues' => array()));
        return rest_ensure_response(array('run' => $run, 'issues' => WPTA_Utils::get_run_issues($run['id'])));
    }
}
