<?php
declare(strict_types=1);

namespace App\Tests\Unit\Service\Mailer;

use App\Entity\Access\Access;
use App\Entity\Message\ReportEmail;
use App\Entity\Person\Person;
use App\Enum\Core\EmailSendingTypeEnum;
use App\Enum\Message\MessageStatusEnum;
use App\Enum\Message\ReportMessageStatusEnum;
use App\Service\Mailer\Builder\BuilderInterface;
use App\Service\Mailer\Email;
use App\Service\Mailer\EmailRecipient;
use App\Service\Mailer\Mailer;
use App\Service\Mailer\Model\MailerModelInterface;
use App\Service\ServiceIterator\Mailer\BuilderIterator;
use App\Service\Utils\Environnement;
use App\Service\Utils\StringsUtils;
use Doctrine\Common\Collections\ArrayCollection;
use Doctrine\ORM\EntityManagerInterface;
use PHPUnit\Framework\MockObject\MockObject;
use PHPUnit\Framework\TestCase;
use Psr\Log\LoggerInterface;
use Ramsey\Uuid\Uuid;
use Symfony\Bridge\Twig\Mime\TemplatedEmail;
use Symfony\Component\Mailer\MailerInterface;
use Symfony\Component\Mime\Address;
use Symfony\Component\Mime\Email as SymfonyEmail;

/**
 * Classe MailerTest qui test le service Mailer
 */
class MailerTest extends TestCase
{
    private string $opentalentNoReplyEmailAddress;
    private MockObject | MailerInterface $symfonyMailer;
    private MockObject | BuilderIterator $builderIterator;
    private MockObject | StringsUtils $stringsUtils;
    private MockObject | EntityManagerInterface $entityManager;
    private MockObject | Environnement $environnement;
    private MockObject | LoggerInterface $logger;

    public function setUp(): void {
        $this->symfonyMailer = $this->getMockBuilder(MailerInterface::class)->disableOriginalConstructor()->getMock();
        $this->opentalentNoReplyEmailAddress = 'noreply@opentalent.fr';
        $this->builderIterator = $this->getMockBuilder(BuilderIterator::class)->disableOriginalConstructor()->getMock();
        $this->stringsUtils = $this->getMockBuilder(StringsUtils::class)->disableOriginalConstructor()->getMock();
        $this->entityManager = $this->getMockBuilder(EntityManagerInterface::class)->disableOriginalConstructor()->getMock();
        $this->environnement = $this->getMockBuilder(Environnement::class)->disableOriginalConstructor()->getMock();
        $this->logger = $this->getMockBuilder(LoggerInterface::class)->disableOriginalConstructor()->getMock();
    }

    /**
     * mailer mock maker
     * @param string $methodUnderTest
     * @return Mailer|MockObject
     */
    private function makeMailerMock(string $methodUnderTest): Mailer | MockObject
    {
        $mailer = $this->getMockBuilder(Mailer::class)
            ->setConstructorArgs([
                $this->symfonyMailer,
                $this->opentalentNoReplyEmailAddress,
                $this->builderIterator,
                $this->stringsUtils,
                $this->entityManager,
                $this->environnement,
                $this->logger,
            ])
            ->setMethodsExcept([$methodUnderTest])
            ->getMock();

        return $mailer;
    }

    private function makeEmailEntity(): \App\Entity\Message\Email | MockObject{
        $person = $this->getMockBuilder(Person::class)->disableOriginalConstructor()->getMock();
        $person->method('getFullName')->willReturn('Ben Yolo');

        $author = $this->getMockBuilder(Access::class)->disableOriginalConstructor()->getMock();
        $author->method('getPerson')->willReturn($person);

        $emailEntity = $this->getMockBuilder(\App\Entity\Message\Email::class)->disableOriginalConstructor()->getMock();
        $emailEntity->method('getAuthor')->willReturn($author);
        $emailEntity->method('getAbout')->willReturn('sujet');
        $emailEntity->method('getUuid')->willReturn(Uuid::fromString('177ef0d8-6630-11ea-b69a-0242ac130003'));

        return $emailEntity;
    }

    /**
     * @see Mailer::main()
     */
    public function testMain(){
        $mailer = $this->makeMailerMock('main');
        $mailerModel = $this->getMockBuilder(MailerModelInterface::class)->disableOriginalConstructor()->getMock();
        $builderService = $this->getMockBuilder(BuilderInterface::class)->disableOriginalConstructor()->getMock();

        $email = $this->getMockBuilder(Email::class)->disableOriginalConstructor()->getMock();
        $email->method('getEmailRecipients')->willReturn(new ArrayCollection());
        $email->method('getEmailEntity')->willReturn(new \App\Entity\Message\Email());

        $emailsCollection = new ArrayCollection([$email]);

        $this->builderIterator
            ->expects(self::once())
            ->method('getBuilderFor')
            ->willReturn($builderService);

        $builderService
            ->expects(self::once())
            ->method('build')
            ->with($mailerModel)
            ->willReturn($emailsCollection)
        ;

        $mailer
            ->expects(self::once())
            ->method('reduceEmailsCollectionInPreproduction')
            ->with($emailsCollection)
            ->willReturn($emailsCollection)
        ;

        $mailer
            ->expects(self::once())
            ->method('sendReport')
            ->with($emailsCollection)
            ;

        $this->entityManager
            ->expects(self::once())
            ->method('flush')
        ;

        $emailsCollection = $mailer->main($mailerModel);

        $this->assertEquals(MessageStatusEnum::NO_RECIPIENT()->getValue(), $email->getEmailEntity()->getStatus());

        $this->assertInstanceOf(Email::class, $emailsCollection->first());
    }

    /**
     * @see Mailer::send()
     */
    public function testSend(){
        $mailer = $this->makeMailerMock('send');

        $email = $this->getMockBuilder(Email::class)->disableOriginalConstructor()->getMock();
        $email->method('getEmailEntity')->willReturn(new \App\Entity\Message\Email());

        $symfonyEmail = $this->getMockBuilder(SymfonyEmail::class)->disableOriginalConstructor()->getMock();
        $symfonyEmail->method('getTo')->willReturn([]);

        $mailer
            ->expects(self::once())
            ->method('createSymfonyEmail')
            ->with($email)
            ->willReturn($symfonyEmail)
        ;

        $mailer
            ->expects(self::once())
            ->method('addRecipients')
            ->with($symfonyEmail, $email)
        ;

        $mailer
            ->expects(self::once())
            ->method('setAntiSpam')
            ->with($email, $symfonyEmail->getTo())
        ;

        $mailer
            ->expects(self::once())
            ->method('setSymfonyEmailContent')
            ->with($symfonyEmail, $email)
        ;

        $mailer
            ->expects(self::once())
            ->method('addHeaders')
            ->with($symfonyEmail, $email)
        ;

        $this->symfonyMailer
            ->expects(self::once())
            ->method('send')
            ->with($symfonyEmail)
        ;

        $mailer->send($email);

        $this->assertEquals(MessageStatusEnum::SEND()->getValue(), $email->getEmailEntity()->getStatus());
    }

    /**
     * @see Mailer::sendReport()
     */
    public function testSendReport(){
        $mailer = $this->makeMailerMock('sendReport');

        $email = $this->getMockBuilder(Email::class)->disableOriginalConstructor()->getMock();
        $templatedEmail = $this->getMockBuilder(TemplatedEmail::class)->disableOriginalConstructor()->getMock();

        $mailer->method('createReportEmail')->willReturn($templatedEmail);
        $this->symfonyMailer->expects(self::once())->method('send')->with($templatedEmail);

        $mailer->sendReport(new ArrayCollection([$email]));
    }

    /**
     * @see Mailer::createReportEmail()
     */
    public function testCreateReportEmail(){
        $mailer = $this->makeMailerMock('createReportEmail');
        $mailer->method('getDeliveredAndUndelivered')->willReturn([[], []]);

        $emailEntity = $this->makeEmailEntity();

        $email = $this->getMockBuilder(Email::class)->disableOriginalConstructor()->getMock();
        $email->method('getEmailEntity')->willReturn($emailEntity);
        $email->method('getFrom')->willReturn('foo.bar@opentalent.fr');
        $email->method('geFromName')->willReturn('Bill');

        $reportEmail = $mailer->createReportEmail(new ArrayCollection([$email]));

        $this->assertInstanceOf(TemplatedEmail::class, $reportEmail);
    }

    /**
     * @see Mailer::getDeliveredAndUndelivered()
     */
    public function testGetDeliveredAndUndelivered(){
        $mailer = $this->makeMailerMock('getDeliveredAndUndelivered');

        $emailRecipient = $this->getMockBuilder(EmailRecipient::class)->disableOriginalConstructor()->getMock();
        $emailRecipient->method('getSendStatus')->willReturn(ReportMessageStatusEnum::MISSING()->getValue());
        $emailRecipient2 = $this->getMockBuilder(EmailRecipient::class)->disableOriginalConstructor()->getMock();
        $emailRecipient2->method('getSendStatus')->willReturn(ReportMessageStatusEnum::DELIVERED()->getValue());
        $email = $this->getMockBuilder(Email::class)->disableOriginalConstructor()->getMock();
        $email->method('getEmailRecipients')->willReturn(new ArrayCollection([$emailRecipient, $emailRecipient2]));

        $emailRecipient3 = $this->getMockBuilder(EmailRecipient::class)->disableOriginalConstructor()->getMock();
        $emailRecipient3->method('getSendStatus')->willReturn(ReportMessageStatusEnum::DELIVERED()->getValue());
        $emailRecipient4 = $this->getMockBuilder(EmailRecipient::class)->disableOriginalConstructor()->getMock();
        $emailRecipient4->method('getSendStatus')->willReturn(ReportMessageStatusEnum::MISSING()->getValue());
        $email2 = $this->getMockBuilder(Email::class)->disableOriginalConstructor()->getMock();
        $email2->method('getEmailRecipients')->willReturn(new ArrayCollection([$emailRecipient3, $emailRecipient4]));

        [$delivered, $undelivered] = $mailer->getDeliveredAndUndelivered(new ArrayCollection([$email, $email2]));

        $this->assertCount(2, $delivered);
        $this->assertCount(2, $undelivered);
    }

    /**
     * @see Mailer::persistEmailEntity()
     */
    public function testPersistEmailEntity(){
        $mailer = $this->makeMailerMock('persistEmailEntity');

        $emailRecipient = $this->getMockBuilder(EmailRecipient::class)->disableOriginalConstructor()->getMock();
        $emailRecipient2 = $this->getMockBuilder(EmailRecipient::class)->disableOriginalConstructor()->getMock();

        $email = $this->getMockBuilder(Email::class)->disableOriginalConstructor()->getMock();
        $emailEntity = $this->makeEmailEntity();

        $email->method('getEmailEntity')->willReturn($emailEntity);
        $email->method('getEmailRecipients')->willReturnOnConsecutiveCalls(new ArrayCollection([$emailRecipient, $emailRecipient2]));

        $emailEntity->expects(self::exactly(2))->method('addReport');
        $this->entityManager->expects(self::once())->method('persist')->with($emailEntity);

        $mailer->persistEmailEntity($email);
    }

    /**
     * @see Mailer::createReport()
     */
    public function testCreateReport(){
        $mailer = $this->makeMailerMock('createReport');

        $access = $this->getMockBuilder(Access::class)->disableOriginalConstructor()->getMock();

        $emailRecipient = $this->getMockBuilder(EmailRecipient::class)->disableOriginalConstructor()->getMock();
        $emailRecipient->method('getEmailAddress')->willReturn('foo.bar@opentalent.fr');
        $emailRecipient->method('getName')->willReturn('Will Farel');
        $emailRecipient->method('getSendType')->willReturn(EmailSendingTypeEnum::TO()->getValue());
        $emailRecipient->method('getAccess')->willReturn($access);
        $emailRecipient->method('getSendStatus')->willReturn(ReportMessageStatusEnum::DELIVERED()->getValue());

        $report = $mailer->createReport($emailRecipient);

        $this->assertInstanceOf(ReportEmail::class, $report);
        $this->assertEquals('foo.bar@opentalent.fr', $report->getAddressEmail());
        $this->assertEquals($access, $report->getAccess());
        $this->assertEquals(ReportMessageStatusEnum::DELIVERED()->getValue(), $report->getStatus());
    }

    /**
     * @see Mailer::reduceEmailsCollectionInPreproduction()
     */
    public function testReduceEmailsCollectionInPreproduction(){
        $mailer = $this->makeMailerMock('reduceEmailsCollectionInPreproduction');
        $environnement = $this->getMockBuilder(Environnement::class)->disableOriginalConstructor()->getMock();
        $environnement->method('get')->willReturn('dev');

        $array = [];
        for($i=0; $i<=50; $i++){
            $array[] = $i;
        }

        $arrayReduced = $mailer->reduceEmailsCollectionInPreproduction(new ArrayCollection($array));

        $this->assertCount(20, $arrayReduced->toArray());

        $array = [];
        for($i=0; $i<=9; $i++){
            $array[] = $i;
        }
        $arrayReduced = $mailer->reduceEmailsCollectionInPreproduction(new ArrayCollection($array));
        $this->assertCount(10, $arrayReduced->toArray());
    }

    /**
     * @see Mailer::addHeaders()
     */
    public function testAddHeaders(){
        $mailer = $this->makeMailerMock('addHeaders');

        $emailEntity = $this->makeEmailEntity();

        $email = $this->getMockBuilder(Email::class)->disableOriginalConstructor()->getMock();
        $email->method('getFrom')->willReturn('foo.bar@opentalent.fr');
        $email->method('getEmailEntity')->willReturn($emailEntity);

        $symfonyMail = new SymfonyEmail();

        $mailer->addHeaders($symfonyMail, $email);

        $this->assertEquals('mailto:foo.bar@opentalent.fr?subject=désabonnement', $symfonyMail->getHeaders()->get('List-Unsubscribe')->getBody());
        $this->assertEquals('177ef0d8-6630-11ea-b69a-0242ac130003', $symfonyMail->getHeaders()->get('X-ID-OT')->getBody());
    }

    /**
     * @see Mailer::setAntiSpam()
     */
    public function testSetAntiSpam(){
        $mailer = $this->makeMailerMock('setAntiSpam');

        $email = new Email();
        $email->setContent('#__#ANTISPAM_PERSON_EMAIL#__#');

        $addressMailFrom = new Address('foo.bar@opentalent.fr', 'Bob dit lane');

        $mailer->setAntiSpam( $email, [$addressMailFrom]);

        $this->assertEquals('foo.bar@opentalent.fr', $email->getContent());
    }

    /**
     * @see Mailer::createSymfonyEmail()
     */
    public function testCreateSymfonyEmail(){
        $mailer = $this->makeMailerMock('createSymfonyEmail');

        $emailEntity = $this->makeEmailEntity();

        $email = $this->getMockBuilder(Email::class)->disableOriginalConstructor()->getMock();
        $email->method('getFrom')->willReturn('foo.bar@opentalent.fr');
        $email->method('geFromName')->willReturn('Ben Yolo');
        $email->method('getEmailEntity')->willReturn($emailEntity);
        $email->method('getContent')->willReturn('contenu');

        $addressMailFrom = new Address($email->getFrom(), $email->geFromName());
        $symfonyMail = $mailer->createSymfonyEmail($email);
        $this->assertInstanceOf(SymfonyEmail::class, $symfonyMail);
        $this->assertEquals($symfonyMail->getFrom(), [$addressMailFrom]);
        $this->assertEquals($symfonyMail->getReplyTo(), [$addressMailFrom]);
        $this->assertEquals($symfonyMail->getReturnPath(), Address::create("mail.report@opentalent.fr"));
        $this->assertEquals($symfonyMail->getSubject(), $emailEntity->getAbout());
    }

    /**
     * @see Mailer::setSymfonyEmailContent()
     */
    public function testSetSymfonyEmailContent(){
        $mailer = $this->makeMailerMock('setSymfonyEmailContent');

        $email = $this->getMockBuilder(Email::class)->disableOriginalConstructor()->getMock();
        $email->method('getContent')->willReturn('contenu');

        $this->stringsUtils
            ->expects(self::once())
            ->method('convertHtmlToText')
            ->willReturn($email->getContent());

        $symfonyMail = new SymfonyEmail();

        $mailer->setSymfonyEmailContent($symfonyMail, $email);

        $this->assertEquals($symfonyMail->getHtmlBody(), $email->getContent());
        $this->assertEquals($symfonyMail->getTextBody(), $email->getContent());
    }

    /**
     * @see Mailer::addRecipients()
     */
    public function testAddRecipients(){
        $mailer = $this->makeMailerMock('addRecipients');
        $symfonyMail = new SymfonyEmail();

        $emailRecipient = $this->getMockBuilder(EmailRecipient::class)->disableOriginalConstructor()->getMock();
        $emailRecipient->method('getEmailAddress')->willReturn('foo.bar@opentalent.fr');
        $emailRecipient->method('getName')->willReturn('Will Farel');
        $emailRecipient->method('getSendType')->willReturn(EmailSendingTypeEnum::TO()->getValue());

        $emailRecipientBBC = $this->getMockBuilder(EmailRecipient::class)->disableOriginalConstructor()->getMock();
        $emailRecipientBBC->method('getEmailAddress')->willReturn('foo.bar@opentalent.fr.bbc');
        $emailRecipientBBC->method('getName')->willReturn('Will Farel');
        $emailRecipientBBC->method('getSendType')->willReturn(EmailSendingTypeEnum::BBC()->getValue());

        $email = $this->getMockBuilder(Email::class)->disableOriginalConstructor()->getMock();
        $email->method('getEmailRecipients')->willReturn(new ArrayCollection([$emailRecipient, $emailRecipientBBC]));

        $mailer->addRecipients($symfonyMail, $email);

        $this->assertCount(1, $symfonyMail->getTo());
        $this->assertCount(1, $symfonyMail->getBcc());
        $this->assertCount(0, $symfonyMail->getCc());
    }
}
