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

use EasyChat\Library\Messenger\Marketplace\MarketplaceCredentialsVault;
use EasyChat\Library\Messenger\Marketplace\MarketplaceProviderInterface;
use EasyChat\Library\Messenger\Marketplace\MarketplaceStream;
use EasyChat\Library\Messenger\OzonProvider;
use EasyChat\Library\Messenger\ProviderRegistry;
use EasyChat\Library\Queue\JobInterface;
use EasyChat\Model\Marketplace as MarketplaceModel;
use EasyChat\Model\Messenger as MessengerModel;

 
class MessengerMarketplaceReadReceiptJob implements JobInterface {
    private $registry;

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

    public function handle(array $payload): void {
        $thread_id = (int)($payload['thread_id'] ?? 0);
        $chat_id = (int)($payload['chat_id'] ?? 0);
        $message_id = (int)($payload['message_id'] ?? 0);
        if ($thread_id <= 0 || $chat_id <= 0 || $message_id <= 0) {
            throw new \InvalidArgumentException('marketplace_read_receipt_payload_invalid');
        }

        $marketplace = new MarketplaceModel($this->registry);
        $thread = $marketplace->getThreadById($thread_id);
        if (!$thread
            || (int)($thread['chat_id'] ?? 0) !== $chat_id
            || (string)($thread['provider'] ?? '') !== OzonProvider::PROVIDER
            || (string)($thread['conversation_kind'] ?? '') !== MarketplaceStream::BUYER_CHAT
        ) {
            return;
        }
        $channel = (new MessengerModel($this->registry))->getChannelById((int)$thread['channel_id']);
        if (!$channel || (string)($channel['status'] ?? '') !== 'active') {
            return;
        }
        $provider = ProviderRegistry::get(OzonProvider::PROVIDER, $this->registry);
        if (!$provider instanceof MarketplaceProviderInterface) {
            throw new \RuntimeException('marketplace_provider_unavailable');
        }
        $provider_capabilities = $provider->marketplaceCapabilities();
        $stored = json_decode((string)($channel['credentials_json'] ?? ''), true);
        $credentials = (new MarketplaceCredentialsVault($this->registry))->open(
            is_array($stored) ? $stored : [],
            is_array($provider_capabilities['secret_fields'] ?? null) ? $provider_capabilities['secret_fields'] : []
        );
        $result = $provider->markMarketplaceThreadRead($credentials, [
            'external_chat_id' => (string)($thread['external_chat_id'] ?? $thread['external_thread_id'] ?? ''),
            'from_message_id' => $message_id,
        ]);
        if (empty($result['success']) && !empty($result['retryable'])) {
            throw new \RuntimeException((string)($result['error'] ?? 'read_receipt_failed'));
        }

         
         
        $marketplace->confirmReadReceipt($thread_id, $message_id);
    }
}
