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

use EasyChat\Library\Messenger\InboundService;
use EasyChat\Library\Messenger\MessengerLogger;
use EasyChat\Library\Queue\JobInterface;
use EasyChat\Library\Queue\RequeueWithoutAttemptException;
use EasyChat\Model\Messenger as MessengerModel;

 
class MessengerMarketplaceAttachmentRetryJob implements JobInterface {
    private $registry;

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

    public function handle(array $payload): void {
        $channel_id = (int)($payload['channel_id'] ?? 0);
        $event = is_array($payload['event'] ?? null) ? $payload['event'] : [];
        $retry_count = max(0, (int)($payload['retry_count'] ?? 0));
        if ($channel_id <= 0 || !$event || strlen((string)json_encode($event)) > 48 * 1024) {
            throw new \InvalidArgumentException('marketplace_attachment_retry_payload_invalid');
        }

        $channel = (new MessengerModel($this->registry))->getChannelById($channel_id);
        $provider = (string)($channel['provider'] ?? '');
        if (!$channel || !in_array($provider, ['wildberries', 'ozon', 'yandex_market'], true) || (string)($channel['status'] ?? '') !== 'active') {
            return;
        }

        $result = (new InboundService($this->registry))->acceptMarketplaceEvent($channel, $event);
        if (empty($result['success'])) {
            throw new \RuntimeException((string)($result['error'] ?? 'marketplace_attachment_retry_failed'));
        }
        if (empty($result['attachment_pending'])) {
            return;
        }

        if ($retry_count >= 7) {
            (new MessengerLogger($this->registry, $provider))->warning('marketplace_attachment_retry_exhausted', [
                'channel_id' => $channel_id,
                'message_hash' => MessengerLogger::hashExternalId((string)($event['external_message_id'] ?? '')),
            ]);
            return;
        }
        $payload['retry_count'] = $retry_count + 1;
        $delays = [30, 60, 120, 240, 480, 900, 1800, 3600];
        throw new RequeueWithoutAttemptException(
            'marketplace_attachment_still_processing',
            $delays[$retry_count] ?? 3600,
            $payload
        );
    }
}
