<?php

declare(strict_types=1);

namespace App\Message\Handler;

use App\Message\Message\OrganizationCreation;
use App\Service\Organization\OrganizationFactory;
use Symfony\Component\Mailer\MailerInterface;
use Symfony\Component\Messenger\Attribute\AsMessageHandler;
use Symfony\Component\Mime\Address;
use Symfony\Component\Mime\Email as SymfonyEmail;
use Symfony\Contracts\HttpClient\Exception\TransportExceptionInterface;

#[AsMessageHandler(priority: 1)]
class OrganizationCreationHandler
{
    public function __construct(
        private readonly OrganizationFactory $organizationFactory,
        private readonly MailerInterface $symfonyMailer,
    ) {
    }

    /**
     * @throws \Throwable
     * @throws TransportExceptionInterface
     * @throws \Symfony\Component\Mailer\Exception\TransportExceptionInterface
     */
    public function __invoke(OrganizationCreation $organizationCreationCommand): void
    {
        $organizationCreationRequest = $organizationCreationCommand->getOrganizationCreationRequest();
        $mail = ['subject' => '', 'content' => ''];

        try {
            $organization = $this->organizationFactory->create($organizationCreationRequest);

            $mail['subject'] = 'New organization created';
            $mail['content'] = 'The organization "'.$organization->getName().'" has been created successfully.';
        } catch (\Exception $e) {
            $mail['subject'] = 'Organization creation : an error occured';
            $mail['content'] = 'An error occured while creating the new organization : \n'.$e->getMessage();
            throw $e;
        } finally {
            if ($organizationCreationRequest->getSendConfirmationEmailAt() !== null) {
                $symfonyMail = (new SymfonyEmail())
                    ->from('mail.report@opentalent.fr')
                    ->replyTo('mail.report@opentalent.fr')
                    ->returnPath(Address::create('mail.report@opentalent.fr'))
                    ->to($organizationCreationRequest->getSendConfirmationEmailAt())
                    ->subject($mail['subject'])
                    ->text($mail['content']);
                $this->symfonyMailer->send($symfonyMail);
            }
        }
    }
}
