<?php

declare(strict_types=1);

namespace ImovelZapAi\Conversations\Application\Actions;

use ImovelZapAi\Conversations\Application\Services\QualificationAnswerParser;
use ImovelZapAi\Conversations\Application\Services\QualificationQuestionCatalog;
use ImovelZapAi\Conversations\Infrastructure\Persistence\Eloquent\ContactModel;
use ImovelZapAi\Conversations\Infrastructure\Persistence\Eloquent\ConversationModel;
use ImovelZapAi\Properties\Infrastructure\Persistence\Eloquent\PropertyInterestModel;
use ImovelZapAi\Tenancy\Support\TenantContext;

final class ProcessQualificationReplyAction
{
    public function __construct(
        private readonly QualificationQuestionCatalog $catalog,
        private readonly QualificationAnswerParser $parser,
        private readonly GenerateConversationSummaryAction $generateSummary,
        private readonly SendOutboundMessageAction $sendText,
    ) {}

    public function execute(
        string $tenantId,
        ContactModel $contact,
        ConversationModel $conversation,
        string $body,
    ): void {
        TenantContext::set($tenantId);

        $qualificationContext = $conversation->context['qualification'] ?? null;

        if (! is_array($qualificationContext)) {
            $this->sendText->execute(
                $tenantId,
                $contact,
                'Não entendi. Um corretor entrará em contato em breve.',
                $conversation,
            );

            return;
        }

        $awaitingField = $qualificationContext['awaiting_field'] ?? null;

        if (! is_string($awaitingField) || $awaitingField === '') {
            return;
        }

        $answers = is_array($qualificationContext['answers'] ?? null)
            ? $qualificationContext['answers']
            : [];

        $parsed = $this->parser->parse($awaitingField, $body);

        if ($parsed !== null) {
            $answers[$awaitingField] = $parsed;
        } elseif ($awaitingField === 'move_timeline') {
            $answers[$awaitingField] = trim($body);
        }

        $interestId = $qualificationContext['property_interest_id'] ?? null;
        $interest = is_string($interestId)
            ? PropertyInterestModel::query()->whereKey($interestId)->first()
            : null;

        if ($interest !== null) {
            $interest->update(['qualification' => $answers]);
        }

        $nextField = $this->catalog->nextField($awaitingField, $answers);

        if ($nextField !== null) {
            $qualificationContext['awaiting_field'] = $nextField;
            $qualificationContext['answers'] = $answers;

            $conversation->update([
                'context' => array_merge($conversation->context ?? [], [
                    'qualification' => $qualificationContext,
                ]),
            ]);

            $message = $this->catalog->transitionFor($nextField) ?? '';
            $question = $this->catalog->questionFor($nextField);
            $body = trim($message) !== '' ? $message."\n".$question : $question;

            $this->sendText->execute($tenantId, $contact, $body, $conversation);

            return;
        }

        if ($interest === null) {
            return;
        }

        $requestedVisit = (bool) ($qualificationContext['requested_visit'] ?? true);

        $this->generateSummary->execute(
            $tenantId,
            $contact,
            $conversation,
            $interest,
            $requestedVisit,
        );
    }
}
