<?php
declare(strict_types=1);

namespace App\Service\Mailer\Builder;

use App\Entity\Access\Access;
use App\Entity\Organization\Organization;
use App\Entity\Organization\Subdomain;
use App\Enum\Core\ContactPointTypeEnum;
use App\Enum\Core\EmailSendingTypeEnum;
use App\Service\Access\Utils as AccessUtils;
use App\Service\Mailer\Email;
use App\Service\Mailer\Model\MailerModelInterface;
use App\Service\Mailer\Model\SubdomainChangeModel;
use App\Tests\Service\Mailer\Builder\OnSubdomainChangeMailBuilderTest;
use Doctrine\Common\Collections\ArrayCollection;
use Doctrine\ORM\EntityManagerInterface;

/**
 * Classe SubDomainChangeBuilder qui est chargé de construire l'Email qui sera envoyé
 */
class OnSubdomainChangeMailBuilder extends AbstractBuilder implements BuilderInterface
{
    public function __construct(
        private EntityManagerInterface $entityManager,
        private string $opentalentNoReplyEmailAddress,
        private AccessUtils $accessUtils
    )
    {
    }

    public function support(MailerModelInterface $mailerModel): bool
    {
        return $mailerModel instanceof SubdomainChangeModel;
    }

    /**
     * @param SubdomainChangeModel $mailerModel
     * @return ArrayCollection
     *
     * @see OnSubdomainChangeMailBuilderTest::testBuild()
     */
    public function build(MailerModelInterface $mailerModel): ArrayCollection
    {
        $subdomain = $this->entityManager->getRepository(Subdomain::class)->find($mailerModel->getSubdomainId());
        $organization = $this->entityManager->getRepository(Organization::class)->find($mailerModel->getOrganizationId());
        $author = $this->entityManager->getRepository(Access::class)->find($mailerModel->getSenderId());
        $admin = $this->accessUtils->findAdminFor($organization);

        $context = [
            'access' => $admin,
            'organization' => $organization,
            'subdomain' => $subdomain,
            'url' => $mailerModel->getUrl()
        ];
        $content = $this->render('subdomain', $context);

        $email= (new Email())
            ->setEmailEntity($this->buildEmailEntity( 'Nouveau sous domaine: ' . $subdomain->getSubdomain(), $author, $content))
            ->setContent($content)
            ->setFrom($this->opentalentNoReplyEmailAddress)
            ->setFromName($organization->getName())
        ;
        $this->addRecipient($email, $admin, EmailSendingTypeEnum::TO()->getValue(), ContactPointTypeEnum::PRINCIPAL()->getValue());

        return new ArrayCollection([$email]);
    }
}