<?php

namespace WPSN\Core\Queue;

defined('ABSPATH') || exit;

/**
 * Queue pause helper.
 *
 * Purpose: allow admins to temporarily pause background processing
 * (WP-Cron queue tick and UI-triggered worker runs) on limited hosting
 * or during incidents.
 *
 * This is intentionally stored outside the main Settings option so it
 * does not pollute Config Sync / Snapshots. It's an operational switch.
 */
final class QueuePause
{
    public const OPTION_UNTIL = 'wpsn_queue_pause_until';
    public const OPTION_REASON = 'wpsn_queue_pause_reason';

    public static function now(): int
    {
        return (int) (function_exists('time') ? time() : 0);
    }

    public static function pauseUntil(): int
    {
        $until = (int) get_option(self::OPTION_UNTIL, 0);
        if ($until < 0) {
            $until = 0;
        }

        // Optional wp-config hard pause.
        if (defined('WPSN_QUEUE_PAUSE') && (bool) WPSN_QUEUE_PAUSE) {
            return max($until, self::now() + 365 * DAY_IN_SECONDS);
        }
        if (defined('WPSN_QUEUE_PAUSE_UNTIL')) {
            $forced = (int) WPSN_QUEUE_PAUSE_UNTIL;
            if ($forced > $until) {
                $until = $forced;
            }
        }

        return $until;
    }

    public static function isPaused(): bool
    {
        return self::pauseUntil() > self::now();
    }

    public static function reason(): string
    {
        $reason = (string) get_option(self::OPTION_REASON, '');
        return $reason !== '' ? $reason : '';
    }

    public static function pause(int $seconds, string $reason = ''): int
    {
        $seconds = max(60, $seconds);
        $until = self::now() + $seconds;
        update_option(self::OPTION_UNTIL, $until, false);
        if ($reason !== '') {
            update_option(self::OPTION_REASON, sanitize_text_field($reason), false);
        }
        return $until;
    }

    public static function resume(): void
    {
        update_option(self::OPTION_UNTIL, 0, false);
        delete_option(self::OPTION_REASON);
    }
}
