<?php

declare(strict_types=1);

namespace ImovelZapAi\Visits\Infrastructure\Messaging;

use ImovelZapAi\Conversations\Application\Actions\SendOutboundMessageAction;
use ImovelZapAi\Conversations\Domain\Enums\MessageDeliveryStatus;
use ImovelZapAi\Conversations\Infrastructure\Persistence\Eloquent\ContactModel;
use ImovelZapAi\Conversations\Infrastructure\Persistence\Eloquent\ConversationModel;
use ImovelZapAi\Visits\Application\Ports\VisitOutboundMessengerInterface;
use RuntimeException;

final class ConversationsVisitOutboundMessenger implements VisitOutboundMessengerInterface
{
    public function __construct(
        private readonly SendOutboundMessageAction $sendOutbound,
    ) {}

    public function send(
        string $tenantId,
        ContactModel $contact,
        string $body,
        ?ConversationModel $conversation = null,
    ): void {
        $message = $this->sendOutbound->execute($tenantId, $contact, $body, $conversation);

        if ($message->delivery_status === MessageDeliveryStatus::Failed) {
            throw new RuntimeException($message->error_message ?? 'Falha ao enviar WhatsApp.');
        }
    }
}
