<?php

namespace App\EntityListener;

use App\Entity\NegotiationMessage;
use App\Message\NegotiationMessage as Message;
use Doctrine\ORM\Mapping\PostPersist;
use Symfony\Component\Messenger\MessageBusInterface;

final class NegotiationMessageListener
{
    /**
     * @var MessageBusInterface
     */
    private $bus;

    public function __construct(MessageBusInterface $bus)
    {
        $this->bus = $bus;
    }

    /**
     * @PostPersist
     *
     * @param NegotiationMessage $negotiationMessage
     */
    public function sendEmail(NegotiationMessage $negotiationMessage)
    {
        if ('INBOUND' === $negotiationMessage->getDirection()) {
            return;
        }

        $id = $negotiationMessage->getId();
        $from = $negotiationMessage->getNegotiation()->getEmail().'@i3x.co.uk';
        $to = $negotiationMessage->getNegotiation()->getProspect()->getEmail();
        $title = 'Do you accept guest posts?';
        $body = $negotiationMessage->getDescription();
        $attachContent = $negotiationMessage->getAttachContentFormat();
        if (null === $to || null === $id || null === $body || null === $attachContent || null === $from) {
            return;
        }
        $message = new Message($id, $from, $to, $title, $body, $attachContent);
        $this->bus->dispatch($message);
    }
}
