<?php

declare(strict_types=1);

namespace ImovelZapAi\Conversations\Application\Actions;

use ImovelZapAi\Conversations\Infrastructure\Persistence\Eloquent\BrokerNoteModel;
use ImovelZapAi\Conversations\Infrastructure\Persistence\Eloquent\ContactModel;
use ImovelZapAi\Tenancy\Support\TenantContext;
use ImovelZapAi\Users\Infrastructure\Persistence\Eloquent\UserModel;
use InvalidArgumentException;

final class CreateBrokerNoteAction
{
    public function execute(
        string $tenantId,
        ContactModel $contact,
        UserModel $author,
        string $body,
        ?string $conversationId = null,
        ?string $propertyId = null,
    ): BrokerNoteModel {
        TenantContext::set($tenantId);

        $body = trim($body);

        if ($body === '') {
            throw new InvalidArgumentException('A nota não pode estar vazia.');
        }

        if (mb_strlen($body) > 2000) {
            throw new InvalidArgumentException('A nota deve ter no máximo 2000 caracteres.');
        }

        return BrokerNoteModel::query()->create([
            'tenant_id' => $tenantId,
            'contact_id' => $contact->id,
            'conversation_id' => $conversationId,
            'property_id' => $propertyId,
            'created_by' => $author->id,
            'body' => $body,
        ]);
    }
}
