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

use EasyChat\Library\Messenger\Marketplace\MarketplaceSyncService;
use EasyChat\Library\Queue\JobInterface;
use EasyChat\Library\Queue\RequeueWithoutAttemptException;

class MessengerMarketplaceSyncJob implements JobInterface {
    private $registry;

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

    public function handle(array $payload): void {
        $stream_id = (int)($payload['stream_id'] ?? 0);
        if ($stream_id <= 0) {
            throw new \InvalidArgumentException('marketplace_stream_id_missing');
        }
        $result = (new MarketplaceSyncService($this->registry))->syncStreamId($stream_id);
        if (!empty($result['success']) && !empty($result['has_more'])) {
            throw new RequeueWithoutAttemptException(
                'marketplace_stream_has_more',
                max(1, min(5, (int)($result['continuation_delay_seconds'] ?? 2))),
                $payload,
                true
            );
        }
    }
}
