<?php
namespace EasyChat\Library\Messenger\Marketplace;

use EasyChat\Library\Messenger\OzonProvider;
use EasyChat\Library\Queue\QueueManager;
use EasyChat\Model\Marketplace as MarketplaceModel;
use EasyChat\Model\Messenger as MessengerModel;







class MarketplaceReadReceiptService {
    private $registry;

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

    public function enqueueForChat(int $chat_id): array {
        if ($chat_id <= 0) {
            return ['queued' => false, 'reason' => 'chat_id_invalid'];
        }
        $thread = (new MarketplaceModel($this->registry))->getThreadByChat($chat_id);
        if (!$thread
            || (string)($thread['provider'] ?? '') !== OzonProvider::PROVIDER
            || (string)($thread['conversation_kind'] ?? '') !== MarketplaceStream::BUYER_CHAT
        ) {
            return ['queued' => false, 'reason' => 'read_receipt_not_supported'];
        }
        $capabilities = $this->decode((string)($thread['capabilities_json'] ?? ''));
        $message_id = max(0, (int)($capabilities['read_ack_message_id'] ?? 0));
        if ($message_id <= 0) {
            return ['queued' => false, 'reason' => 'nothing_to_acknowledge'];
        }
        $channel = (new MessengerModel($this->registry))->getChannelById((int)$thread['channel_id']);
        if (!$channel || (string)($channel['status'] ?? '') !== 'active') {
            return ['queued' => false, 'reason' => 'marketplace_channel_inactive'];
        }
        $channel_capabilities = $this->decode((string)($channel['capabilities_json'] ?? ''));
        $allowed = $channel_capabilities['stream_access'][MarketplaceStream::BUYER_CHAT]['action_access']['buyer_chat_read'] ?? null;
        if ($allowed === false) {
            return ['queued' => false, 'reason' => 'read_receipt_permission_missing'];
        }

        $thread_id = (int)$thread['thread_id'];
        $job_id = (new QueueManager($this->registry))->pushUnique(
            'messenger_marketplace_read_receipt',
            ['thread_id' => $thread_id, 'chat_id' => $chat_id, 'message_id' => $message_id],
            'marketplace_read_' . $thread_id . '_' . $message_id,
            0,
            12
        );
        return ['queued' => $job_id > 0, 'job_id' => $job_id];
    }

    private function decode(string $json): array {
        $value = json_decode($json, true);
        return is_array($value) ? $value : [];
    }
}
