<?php

namespace App\Services\CmsUpdate;

/**
 * Pseudo-cron wrapper for CmsUpdateChecker.
 *
 * Uses a lockfile (storage/temp/cms_update_last_run) to debounce
 * the network check to at most once per TTL interval.
 * Mirrors the pattern used by Marketplace\IntegrityMonitor.
 */
class CmsUpdatePseudoCron
{
    private string $basePath;
    private string $lockFile;

    public function __construct(string $basePath)
    {
        $this->basePath = rtrim($basePath, '/\\');
        $this->lockFile = $this->basePath . '/storage/temp/cms_update_last_run';
    }

    /**
     * Delegate to CmsUpdateChecker::runIfDue() with additional lockfile guard.
     * Called from App::handle() on every request (exits silently on error).
     */
    public function runIfDue(): void
    {
        // Quick lockfile debounce (60 s minimum) to prevent burst on every request
        // before the TTL check in CmsUpdateChecker takes over.
        if (is_file($this->lockFile)) {
            $last = (int) file_get_contents($this->lockFile);
            if ((time() - $last) < 60) {
                return;
            }
        }

        @file_put_contents($this->lockFile, (string) time());

        try {
            $checker = new CmsUpdateChecker($this->basePath);
            $checker->runIfDue();
        } catch (\Throwable $e) {
            error_log('CmsUpdatePseudoCron: ' . $e->getMessage());
        }
    }
}
