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

use EasyChat\Library\Messenger\VkCallbackRepairService;
use EasyChat\Library\Queue\RequeueWithoutAttemptException;

class MessengerVkCallbackRepairJob {
    private $registry;

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

    public function handle(array $payload): void {
        $result = (new VkCallbackRepairService($this->registry))->repairByPayload($payload);
        if (!empty($result['success'])) {
            return;
        }

        if (!empty($result['rate_limited'])) {
            $delay = max(60, min(3600, (int)($result['retry_after'] ?? 300)));
            throw new RequeueWithoutAttemptException('vk_callback_repair_rate_limited', $delay, $payload);
        }

        throw new \Exception((string)($result['error'] ?? 'vk_callback_repair_failed'));
    }
}
