<?php
namespace EasyChat\Library\Queue\Jobs;

use EasyChat\Library\Queue\JobInterface;
use EasyChat\Model\Setting;

class SchedulerProbeJob implements JobInterface {
    private $registry;

    public function __construct($registry) {
        $this->registry = $registry;
    }

    public function handle(array $payload): void {
        $probe_id = strtolower(trim((string)($payload['probe_id'] ?? '')));
        if (!preg_match('/^[a-f0-9]{32}$/', $probe_id)) {
            throw new \RuntimeException('scheduler_probe_invalid');
        }
        $model = new Setting($this->registry);
        $pending = (string)$model->get('chat_scheduler_probe_pending_id', '');
        if ($pending === '' || !hash_equals($pending, $probe_id)) {
            return;
        }
        $model->setMany(array(
            'chat_scheduler_probe_completed_id' => $probe_id,
            'chat_scheduler_probe_completed_at' => date('c'),
            'chat_scheduler_probe_pending_id' => '',
        ));
    }
}
