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

use EasyChat\Library\Messenger\InboundService;
use EasyChat\Library\Messenger\WildberriesProvider;
use EasyChat\Model\Messenger as MessengerModel;








final class MarketplaceAnswerProjector {
    private $registry;

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

    public function project(array $thread, string $action, string $text, int $manager_id): array {
        $provider = strtolower((string)($thread['provider'] ?? ''));
        $kind = MarketplaceStream::normalize((string)($thread['conversation_kind'] ?? ''));
        $external_thread_id = trim((string)($thread['external_thread_id'] ?? ''));
        $channel_id = (int)($thread['channel_id'] ?? 0);
        $chat_id = (int)($thread['chat_id'] ?? 0);
        $text = MarketplaceText::truncate(trim($text), 5000);
        $allowed_actions = ['question_answer', 'review_answer', 'review_edit'];
        if (
            $provider !== WildberriesProvider::PROVIDER
            || !in_array($kind, [MarketplaceStream::QUESTION, MarketplaceStream::REVIEW], true)
            || !in_array($action, $allowed_actions, true)
            || $external_thread_id === ''
            || $channel_id <= 0
            || $chat_id <= 0
            || $text === ''
        ) {
            return ['success' => false, 'error' => 'marketplace_answer_projection_invalid'];
        }

        $channel = (new MessengerModel($this->registry))->getChannelById($channel_id);
        if (!$channel || (string)($channel['status'] ?? '') !== 'active') {
            return ['success' => false, 'error' => 'marketplace_channel_inactive'];
        }

        $snapshot = json_decode((string)($thread['snapshot_json'] ?? ''), true);
        $snapshot = is_array($snapshot) ? $snapshot : [];
        $payload = is_array($snapshot['provider_payload'] ?? null) ? $snapshot['provider_payload'] : [];
        $item_context = is_array($snapshot['item_context'] ?? null) ? $snapshot['item_context'] : [];
        $external_message_id = $kind . ':' . $external_thread_id . ':answer';
        $now = gmdate('Y-m-d\TH:i:s\Z');
        $display_name = MarketplaceText::truncate(trim((string)($payload['userName'] ?? '')), 255);
        if ($display_name === '') {
            $display_name = 'Покупатель Wildberries';
        }
        $event = [
            'update_type' => $kind . '_answer',
            'text' => $text,
            'external_user_id' => $kind . ':' . $external_thread_id,
            'external_chat_id' => $kind . ':' . $external_thread_id,
            'external_message_id' => $external_message_id,
            'dedupe_key' => 'wb:' . $kind . ':' . $external_thread_id . ':answer',
            'direction' => 'out',
            'display_name' => $display_name,
            'attachments' => [],
            'conversation_kind' => $kind,
            'external_thread_id' => $external_thread_id,
            'thread_state' => 'answered',
            'item_context' => $item_context,
            'capabilities' => [
                'can_reply' => false,
                'draft_only' => true,
                'actions' => $kind === MarketplaceStream::REVIEW ? ['review_edit'] : [],
            ],
            'published_at' => $now,
            'manager_id' => max(0, $manager_id),
            'metadata' => [
                'marketplace' => true,
                'quiet_import' => false,
                'raw_kind' => 'wb_' . $kind . '_answer',
                'sync_origin' => 'action_projection',
                'mutable_external_message' => true,
                'mutable_event_date' => true,
            ],
            'snapshot' => $payload,
        ];

        $accepted = (new InboundService($this->registry))->acceptMarketplaceEvent($channel, $event);
        if (
            empty($accepted['success'])
            || (int)($accepted['chat_id'] ?? 0) !== $chat_id
            || (int)($accepted['message_id'] ?? 0) <= 0
        ) {
            return ['success' => false, 'error' => 'marketplace_answer_projection_failed'];
        }
        return [
            'success' => true,
            'chat_id' => $chat_id,
            'message_id' => (int)$accepted['message_id'],
            'updated' => !empty($accepted['updated']),
            'duplicate' => !empty($accepted['duplicate']),
        ];
    }
}
