<?php
namespace EasyChat\Library\Messenger;

use EasyChat\Library\Queue\QueueManager;
use EasyChat\Model\Messenger as MessengerModel;
use EasyChat\Model\MessengerItemContext;
use EasyChat\Model\Setting;

class AvitoItemContextService {
    private const JOB_TYPE = 'messenger_avito_item_context_enrich';
    private const DEDUPE_WINDOW_SECONDS = 60;

    private $registry;
    private $db;
    private $prefix;
    private $logger;

    public function __construct($registry) {
        $this->registry = $registry;
        $this->db = $registry->get('db');
        $this->prefix = easychat_db_prefix();
        $this->logger = new MessengerLogger($registry, AvitoProvider::PROVIDER);
    }

    public function remember(int $channel_id, array $context, string $reason = 'context_seen'): array {
        $item_id = trim((string)($context['item_id'] ?? $context['id'] ?? ''));
        if ($channel_id <= 0 || $item_id === '') {
            return [];
        }

        $model = new MessengerItemContext($this->registry);
        $row = $model->upsertSnapshot(AvitoProvider::PROVIDER, $channel_id, $item_id, $context);
         
         
         
        $delay = $reason === 'webhook_context' ? 0 : 10;
        $this->enqueueIfDue($channel_id, $item_id, $reason, $delay);
        return $row;
    }

    public function enqueueIfDue(int $channel_id, string $item_id, string $reason = 'context_seen', int $delay = 10): bool {
        $item_id = trim($item_id);
        if ($channel_id <= 0 || $item_id === '') {
            return false;
        }

        try {
            $model = new MessengerItemContext($this->registry);
            if (!$model->shouldEnrich(AvitoProvider::PROVIDER, $channel_id, $item_id)) {
                return false;
            }
            if ($this->hasRecentQueueJob($channel_id, $item_id)) {
                return false;
            }
            (new QueueManager($this->registry))->push(self::JOB_TYPE, [
                'channel_id' => $channel_id,
                'item_id' => mb_substr($item_id, 0, 64, 'UTF-8'),
                'reason' => mb_substr($reason, 0, 64, 'UTF-8'),
            ], max(0, min(300, $delay)), 3);
            return true;
        } catch (\Throwable $e) {
            $this->logger->warning('avito_item_context_enqueue_failed', [
                'channel_id' => $channel_id,
                'item_hash' => MessengerLogger::hashExternalId($item_id),
                'error' => $this->safeError($e->getMessage()),
            ]);
            return false;
        }
    }

    public function syncByPayload(array $payload, array $http_options = []): array {
        $channel_id = (int)($payload['channel_id'] ?? 0);
        $item_id = trim((string)($payload['item_id'] ?? ''));
        if ($channel_id <= 0 || $item_id === '') {
            return ['success' => true, 'skip' => 'payload_incomplete'];
        }

        $model = new MessengerItemContext($this->registry);
        $messenger = new MessengerModel($this->registry);
        $channel = $messenger->getChannelById($channel_id);
        if (!$channel || (string)($channel['provider'] ?? '') !== AvitoProvider::PROVIDER || (string)($channel['status'] ?? '') !== 'active') {
            $model->markUnavailable(AvitoProvider::PROVIDER, $channel_id, $item_id, 'failed', 'channel_inactive');
            return ['success' => true, 'skip' => 'channel_inactive'];
        }

        $credentials = json_decode((string)($channel['credentials_json'] ?? ''), true);
        $token = is_array($credentials) ? $this->avitoTokenFromCredentials($credentials) : '';
        $account_user_id = preg_replace('/\D+/', '', (string)($channel['bot_user_id'] ?? ''));
        if ($token === '' || $account_user_id === '') {
            $model->markUnavailable(AvitoProvider::PROVIDER, $channel_id, $item_id, 'failed', 'auth_missing');
            return ['success' => false, 'error' => 'auth_missing'];
        }

        $provider = new AvitoProvider($this->registry);
        $result = $provider->getItemInfo($token, $account_user_id, $item_id, $http_options);
        if (empty($result['success'])) {
            $http_code = (int)($result['http_code'] ?? 0);
            $error = $this->safeError((string)($result['error'] ?? 'item_context_lookup_failed'));
            if (in_array($http_code, [403, 404, 405], true)) {
                $model->markUnavailable(AvitoProvider::PROVIDER, $channel_id, $item_id, 'unsupported', $error);
                return ['success' => true, 'skip' => 'item_api_unsupported'];
            }
            $model->markUnavailable(AvitoProvider::PROVIDER, $channel_id, $item_id, 'failed', $error);
            return ['success' => false, 'error' => $error ?: 'item_context_lookup_failed'];
        }

        $item = is_array($result['item_context'] ?? null) ? $result['item_context'] : [];
        if (!$item) {
            $model->markUnavailable(AvitoProvider::PROVIDER, $channel_id, $item_id, 'unsupported', 'item_context_empty');
            return ['success' => true, 'skip' => 'item_context_empty'];
        }

        $model->markEnriched(AvitoProvider::PROVIDER, $channel_id, $item_id, $item);
        return ['success' => true, 'item_id' => $item_id];
    }

    private function hasRecentQueueJob(int $channel_id, string $item_id): bool {
        $since = time() - self::DEDUPE_WINDOW_SECONDS;
        $channel_needle = '%"channel_id":' . (int)$channel_id . '%';
        $item_needle = '%"item_id":"' . $this->db->escape($item_id) . '"%';
        $query = $this->db->query(
            "SELECT `id`
             FROM `{$this->prefix}queue`
             WHERE `job_type` = '" . self::JOB_TYPE . "'
               AND `status` IN ('pending', 'processing')
               AND `created_at` >= " . (int)$since . "
               AND `payload` LIKE '" . $this->db->escape($channel_needle) . "'
               AND `payload` LIKE '" . $this->db->escape($item_needle) . "'
             LIMIT 1"
        );
        return $query && $query->num_rows > 0;
    }

    private function avitoTokenFromCredentials(array $credentials): string {
        $token = $this->decryptSecretOrPlain((string)($credentials['bot_token'] ?? ''));
        if ($token !== '') {
            return $token;
        }
        $client_id = $this->decryptSecretOrPlain((string)($credentials['client_id'] ?? ''));
        $client_secret = $this->decryptSecretOrPlain((string)($credentials['client_secret'] ?? ''));
        if ($client_id === '' || $client_secret === '') {
            return '';
        }
        return json_encode([
            'client_id' => $client_id,
            'client_secret' => $client_secret,
        ], JSON_UNESCAPED_UNICODE);
    }

    private function decryptSecretOrPlain(string $stored): string {
        $stored = trim($stored);
        if ($stored === '') {
            return '';
        }
        if (strpos($stored, 'enc:v1:') !== 0) {
            return $stored;
        }
        $install_secret = (new Setting($this->registry))->get('chat_install_secret', '');
        return $install_secret !== '' ? SecretBox::decrypt($stored, $install_secret) : '';
    }

    private function safeError(string $error): string {
        $error = preg_replace('/[^a-z0-9_:-]/i', '_', $error);
        return mb_substr(trim((string)$error), 0, 120, 'UTF-8');
    }
}
