<?php

declare(strict_types=1);

namespace ImovelZapAi\Conversations\Application\Services;

use ImovelZapAi\Conversations\Application\Data\BrokerReplySuggestionContextData;
use ImovelZapAi\Conversations\Application\Queries\ConversationThreadQuery;
use ImovelZapAi\Conversations\Infrastructure\Persistence\Eloquent\ContactModel;
use ImovelZapAi\Conversations\Infrastructure\Persistence\Eloquent\ConversationModel;
use ImovelZapAi\Conversations\Infrastructure\Persistence\Eloquent\ConversationSummaryModel;
use ImovelZapAi\Users\Infrastructure\Persistence\Eloquent\UserModel;

final class BrokerReplySuggestionContextAssembler
{
    public function __construct(
        private readonly ConversationThreadQuery $threadQuery,
    ) {}

    public function assemble(
        string $tenantId,
        ContactModel $contact,
        ConversationModel $conversation,
        UserModel $broker,
    ): BrokerReplySuggestionContextData {
        $thread = $this->threadQuery->forConversation($conversation);

        $recentMessages = $thread
            ->map(fn ($message): string => $message->senderLabel.': '.$message->body)
            ->values()
            ->all();

        $lastClientMessage = $thread
            ->filter(fn ($message): bool => $message->direction === \ImovelZapAi\Conversations\Domain\Enums\MessageDirection::Inbound)
            ->last()
            ?->body;

        $summary = ConversationSummaryModel::query()
            ->where('tenant_id', $tenantId)
            ->where('conversation_id', $conversation->id)
            ->orderByDesc('created_at')
            ->first();

        $structured = is_array($summary?->structured) ? $summary->structured : [];
        $bullets = is_array($structured['bullets'] ?? null) ? $structured['bullets'] : [];
        $favorites = is_array($structured['favorite_property_codes'] ?? null)
            ? $structured['favorite_property_codes']
            : (is_array($structured['liked_property_codes'] ?? null) ? $structured['liked_property_codes'] : []);
        $flags = is_array($structured['flags'] ?? null) ? $structured['flags'] : [];

        return new BrokerReplySuggestionContextData(
            tenantId: $tenantId,
            conversationId: (string) $conversation->id,
            clientName: trim((string) ($contact->display_name ?: 'Cliente')),
            lastClientMessage: is_string($lastClientMessage) ? trim($lastClientMessage) : null,
            recentMessages: $recentMessages,
            summaryBullets: array_values(array_map('strval', $bullets)),
            recommendedNextStep: is_string($structured['recommended_next_step'] ?? null)
                ? $structured['recommended_next_step']
                : null,
            favoritePropertyCodes: array_values(array_map('strval', $favorites)),
            requestedVisit: ($flags['requested_visit'] ?? false) === true,
            brokerName: trim($broker->name) !== '' ? trim($broker->name) : 'Corretor',
        );
    }
}
