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

use EasyChat\Library\Messenger\OutboundService;
use EasyChat\Library\Queue\RequeueWithoutAttemptException;
use Exception;

class MessengerOutboundJob {

    private $registry;

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

    public function handle(array $payload): void {
        $message_id = (int)($payload['message_id'] ?? 0);
        if ($message_id <= 0) {
            throw new Exception('message_id_required');
        }

        $service = new OutboundService($this->registry);
        $result = $service->sendMessageId($message_id, true);
        if (empty($result['success']) && !empty($result['retryable'])) {
            if (!empty($result['retry_without_attempt'])) {
                $delay = max(5, min(3600, (int)($result['retry_after_seconds'] ?? 60)));
                throw new RequeueWithoutAttemptException(
                    (string)($result['error'] ?? 'messenger_outbound_rate_limited'),
                    $delay,
                    $payload
                );
            }
            throw new Exception((string)($result['error'] ?? 'messenger_outbound_failed'));
        }

         
         
    }
}
