<?php

declare(strict_types=1);

namespace ImovelZapAi\Conversations\Application\Services;

use ImovelZapAi\Conversations\Application\Data\ConversationSummaryContextData;
use ImovelZapAi\Conversations\Application\Data\ConversationSummaryResultData;
use ImovelZapAi\Conversations\Infrastructure\Persistence\Eloquent\ContactModel;
use ImovelZapAi\Conversations\Infrastructure\Persistence\Eloquent\ConversationModel;

final class ConversationSummaryGenerator
{
    public function __construct(
        private readonly ConversationSummaryContextAssembler $assembler,
        private readonly ConversationSummaryAiGenerator $aiGenerator,
        private readonly ConversationSummaryRuleGenerator $ruleGenerator,
    ) {}

    /**
     * @param  array<string, mixed>  $qualification
     * @return array{body: string, structured: array<string, mixed>}
     */
    public function build(
        string $tenantId,
        ContactModel $contact,
        ConversationModel $conversation,
        array $qualification,
        array $likedPropertyCodes,
        bool $requestedVisit,
    ): array {
        $context = $this->assembler->assemble(
            $tenantId,
            $contact,
            $conversation,
            $qualification,
            $requestedVisit,
        );

        $result = $this->aiGenerator->generate($context)
            ?? $this->ruleGenerator->generate($context);

        return [
            'body' => $result->body,
            'structured' => $result->structured,
        ];
    }

    public function fromContext(ConversationSummaryContextData $context): ConversationSummaryResultData
    {
        return $this->aiGenerator->generate($context)
            ?? $this->ruleGenerator->generate($context);
    }
}
