<?php

namespace HaoZiTeam\AIPost\Service\Features;

defined('ABSPATH') || exit;

class CronUtils {
    public static function lock_key(string $taskKey): string {
        return 'ai_post_lock_' . md5($taskKey);
    }

    public static function last_run_key(string $taskKey): string {
        return 'ai_post_last_run_' . md5($taskKey);
    }

    public static function acquire_lock(string $taskKey, int $ttl = 900): bool {
        $key = self::lock_key($taskKey);
        if (get_transient($key)) {
            return false; // already locked
        }
        return set_transient($key, time(), $ttl);
    }

    public static function release_lock(string $taskKey): void {
        delete_transient(self::lock_key($taskKey));
    }

    public static function update_last_run(string $taskKey): void {
        update_option(self::last_run_key($taskKey), time(), false);
    }

    public static function get_last_run(string $taskKey): int {
        return intval(get_option(self::last_run_key($taskKey), 0));
    }

    public static function due_for_catchup(string $taskKey, int $frequencyMinutes): bool {
        $last = self::get_last_run($taskKey);
        // 首次（尚无 last_run 记录）不视为“需要补发”，避免新建任务被立即判定为长时间未跑
        if ($last <= 0) { return false; }
        $elapsed = (time() - $last) / 60;
        return $elapsed >= max(1, $frequencyMinutes);
    }
}
