<?php

namespace HaoZiTeam\AIPost\Service\Features;

defined('ABSPATH') || exit;

class CronEndpoint {
    public static function register(): void {
        add_action('rest_api_init', [__CLASS__, 'register_routes']);
    }

    public static function register_routes(): void {
        register_rest_route('aipost/v1', '/cron', [
            'methods'  => 'POST',
            'callback' => [__CLASS__, 'handle'],
            'permission_callback' => '__return_true', // 将通过token控制
            'args' => [
                'token' => [ 'required' => true, 'type' => 'string' ],
                'key'   => [ 'required' => false, 'type' => 'string' ],
            ],
        ]);

        // 仅用于连通性/令牌有效性自检，不触发任务
        register_rest_route('aipost/v1', '/cron/ping', [
            // 为了便于在浏览器直接调试，允许 GET 与 POST
            'methods'  => ['GET','POST'],
            'callback' => [__CLASS__, 'handle_ping'],
            'permission_callback' => '__return_true',
            'args' => [
                'token' => [ 'required' => true, 'type' => 'string' ],
            ],
        ]);
    }

    public static function handle(\WP_REST_Request $req) {
        $token = trim((string)$req->get_param('token'));
        $key   = $req->get_param('key');

        $saved = get_option('ai_post_cron_token');
        if (!$saved || !hash_equals((string)$saved, (string)$token)) {
            return new \WP_REST_Response([ 'ok' => false, 'error' => 'invalid_token' ], 403);
        }

        if ($key !== null) {
            do_action('ai_post_cron', $key);
            return new \WP_REST_Response([ 'ok' => true, 'trigger' => $key ]);
        }

        // 触发所有开启的任务（安全：仅触发一次执行逻辑，自带锁）
        $settings = get_option('ai-post');
        $count = 0;
        if (!empty($settings['tasks']) && is_array($settings['tasks'])) {
            foreach ($settings['tasks'] as $k => $task) {
                if (!empty($task['task-status'])) {
                    do_action('ai_post_cron', $k);
                    $count++;
                }
            }
        }
        return new \WP_REST_Response([ 'ok' => true, 'triggered' => $count ]);
    }

    // 自检：仅校验 token 有效性，返回站点/时间/版本等辅助信息
    public static function handle_ping(\WP_REST_Request $req) {
        $token = trim((string)$req->get_param('token'));
        $saved = get_option('ai_post_cron_token');
        if (!$saved || !hash_equals((string)$saved, (string)$token)) {
            return new \WP_REST_Response([ 'ok' => false, 'error' => 'invalid_token' ], 403);
        }
        $site  = get_site_url();
        $time  = current_time('mysql');
        $ver   = defined('HAOZI_AIPOST_VERSION') ? HAOZI_AIPOST_VERSION : (defined('HaoZiTeam\\AIPost\\VERSION') ? \HaoZiTeam\AIPost\VERSION : 'unknown');
        return new \WP_REST_Response([
            'ok' => true,
            'site' => $site,
            'time' => $time,
            'version' => $ver,
        ]);
    }
}

// 自动注册
CronEndpoint::register();
