<?php

namespace App\Tests\Unit\Service\Typo3;


use App\Entity\Access\Access;
use App\Entity\Organization\Organization;
use App\Entity\Organization\Subdomain;
use App\Entity\Person\Person;
use App\Message\Command\MailerCommand;
use App\Message\Command\Typo3\Typo3UpdateCommand;
use App\Repository\Access\AccessRepository;
use App\Repository\Organization\SubdomainRepository;
use App\Service\Mailer\Model\SubdomainChangeModel;
use App\Service\Organization\Utils as OrganizationUtils;
use App\Service\Typo3\BindFileService;
use App\Service\Typo3\SubdomainService;
use Doctrine\Common\Collections\ArrayCollection;
use Doctrine\ORM\EntityManagerInterface;
use PHPUnit\Framework\MockObject\MockObject;
use PHPUnit\Framework\TestCase;
use Symfony\Component\Messenger\Envelope;
use Symfony\Component\Messenger\MessageBusInterface;

class TestableSubdomainService extends SubdomainService {
    public function setOrganizationActiveSubdomain(Subdomain $subdomain): Subdomain {
        return parent::setOrganizationActiveSubdomain($subdomain);
    }

    public function renameAdminUserToMatchSubdomain(Subdomain $subdomain): void {
        parent::renameAdminUserToMatchSubdomain($subdomain);
    }

    public function updateTypo3Website($organization): void {
        parent::updateTypo3Website($organization);
    }

    public function getMailModel(Subdomain $subdomain): SubdomainChangeModel
    {
        return parent::getMailModel($subdomain);
    }

    public function sendConfirmationEmail(Subdomain $subdomain): void {
        parent::sendConfirmationEmail($subdomain);
    }
}
class SubdomainServiceTest extends TestCase
{
    private SubdomainRepository $subdomainRepository;
    private OrganizationUtils $organizationUtils;
    private BindFileService $bindFileService;
    private MessageBusInterface $messageBus;
    private EntityManagerInterface $entityManager;
    private AccessRepository $accessRepository;

    public function setUp():void
    {
        $this->subdomainRepository = $this->getMockBuilder(SubdomainRepository::class)->disableOriginalConstructor()->getMock();
        $this->entityManager = $this->getMockBuilder(EntityManagerInterface::class)->disableOriginalConstructor()->getMock();
        $this->messageBus = $this->getMockBuilder(MessageBusInterface::class)->disableOriginalConstructor()->getMock();
        $this->organizationUtils = $this->getMockBuilder(OrganizationUtils::class)->disableOriginalConstructor()->getMock();
        $this->bindFileService = $this->getMockBuilder(BindFileService::class)->disableOriginalConstructor()->getMock();
        $this->accessRepository = $this->getMockBuilder(AccessRepository::class)->disableOriginalConstructor()->getMock();
    }

    private function makeSubdomainServiceMockFor(string $methodName): MockObject | TestableSubdomainService {
        return $this->getMockBuilder(TestableSubdomainService::class)
            ->setConstructorArgs([
                $this->subdomainRepository,
                $this->entityManager,
                $this->messageBus,
                $this->organizationUtils,
                $this->bindFileService,
                $this->accessRepository
            ])
            ->setMethodsExcept([$methodName])
            ->getMock();
    }

    /**
     * @see SubdomainService::canRegisterNewSubdomain()
     */
    public function testCanRegisterNewSubdomainTrue(): void
    {
        $subdomainService = $this->makeSubdomainServiceMockFor('canRegisterNewSubdomain');

        $organization = $this->getMockBuilder(Organization::class)->disableOriginalConstructor()->getMock();
        $organization->expects(self::once())->method('getSubdomains')->willReturn(new ArrayCollection([1, 2]));

        $this->assertTrue($subdomainService->canRegisterNewSubdomain($organization));
    }

    /**
     * @see SubdomainService::canRegisterNewSubdomain()
     */
    public function testCanRegisterNewSubdomainFalse(): void
    {
        $subdomainService = $this->makeSubdomainServiceMockFor('canRegisterNewSubdomain');

        $organization = $this->getMockBuilder(Organization::class)->disableOriginalConstructor()->getMock();
        $organization->expects(self::once())->method('getSubdomains')->willReturn(new ArrayCollection([1, 2, 3]));

        $this->assertFalse($subdomainService->canRegisterNewSubdomain($organization));
    }

    /**
     * @see SubdomainService::isValidSubdomain()
     */
    public function testIsValidSubdomain(): void {
        $subdomainService = $this->makeSubdomainServiceMockFor('isValidSubdomain');

        $this->assertTrue($subdomainService->isValidSubdomain('abcd'));
        $this->assertTrue($subdomainService->isValidSubdomain('abcdefgh'));
        $this->assertTrue($subdomainService->isValidSubdomain('abcd-efgh'));
        $this->assertTrue($subdomainService->isValidSubdomain('123'));
        $this->assertTrue($subdomainService->isValidSubdomain('a'));

        $this->assertFalse($subdomainService->isValidSubdomain('_abc'));
        $this->assertFalse($subdomainService->isValidSubdomain('abc-'));
        $this->assertFalse($subdomainService->isValidSubdomain(str_repeat('abcdef', 20)));
    }

    public function testAddNewSubdomain(): void {
        $subdomainService = $this->makeSubdomainServiceMockFor('addNewSubdomain');

        $organization = $this->getMockBuilder(Organization::class)->disableOriginalConstructor()->getMock();

        $subdomainService->expects(self::once())->method('isValidSubdomain')->with('sub')->willReturn(True);
        $subdomainService->expects(self::once())->method('canRegisterNewSubdomain')->with($organization)->willReturn(True);
        $this->subdomainRepository->expects(self::once())->method('findBy')->with(['subdomain' => 'sub'])->willReturn(0);

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

        $this->bindFileService->expects(self::once())->method('registerSubdomain')->with('sub');

        // Subdomain is not activated by default
        $subdomainService->expects(self::never())->method('activateSubdomain');

        $subdomain = $subdomainService->addNewSubdomain($organization, 'sub');

        $this->assertEquals($subdomain->getOrganization(), $organization);
        $this->assertEquals($subdomain->getSubdomain(), 'sub');
        $this->assertFalse($subdomain->isActive());
    }

    public function testAddNewSubdomainInvalid(): void
    {
        $subdomainService = $this->makeSubdomainServiceMockFor('addNewSubdomain');

        $organization = $this->getMockBuilder(Organization::class)->disableOriginalConstructor()->getMock();

        $subdomainService->expects(self::once())->method('isValidSubdomain')->with('_sub')->willReturn(False);
        $subdomainService->expects(self::never())->method('canRegisterNewSubdomain')->with($organization)->willReturn(True);
        $this->subdomainRepository->expects(self::never())->method('findBy')->with(['subdomain' => '_sub'])->willReturn(0);

        $this->entityManager->expects(self::never())->method('persist');
        $this->entityManager->expects(self::never())->method('flush');
        $this->bindFileService->expects(self::never())->method('registerSubdomain')->with('_sub');
        $subdomainService->expects(self::never())->method('activateSubdomain');

        $this->expectException(\RuntimeException::class);
        $this->expectExceptionMessage('Not a valid subdomain');

        $subdomainService->addNewSubdomain($organization, '_sub');
    }

    public function testAddNewSubdomainMaxReached(): void
    {
        $subdomainService = $this->makeSubdomainServiceMockFor('addNewSubdomain');

        $organization = $this->getMockBuilder(Organization::class)->disableOriginalConstructor()->getMock();

        $subdomainService->expects(self::once())->method('isValidSubdomain')->with('_sub')->willReturn(true);
        $subdomainService->expects(self::once())->method('canRegisterNewSubdomain')->with($organization)->willReturn(false);
        $this->subdomainRepository->expects(self::never())->method('findBy')->with(['subdomain' => '_sub'])->willReturn(0);

        $this->entityManager->expects(self::never())->method('persist');
        $this->entityManager->expects(self::never())->method('flush');
        $this->bindFileService->expects(self::never())->method('registerSubdomain')->with('_sub');
        $subdomainService->expects(self::never())->method('activateSubdomain');

        $this->expectException(\RuntimeException::class);
        $this->expectExceptionMessage('This organization can not register new subdomains');

        $subdomainService->addNewSubdomain($organization, '_sub');
    }

    public function testAddNewSubdomainExisting(): void
    {
        $subdomainService = $this->makeSubdomainServiceMockFor('addNewSubdomain');

        $organization = $this->getMockBuilder(Organization::class)->disableOriginalConstructor()->getMock();

        $subdomainService->expects(self::once())->method('isValidSubdomain')->with('sub')->willReturn(true);
        $subdomainService->expects(self::once())->method('canRegisterNewSubdomain')->with($organization)->willReturn(true);
        $this->subdomainRepository->expects(self::once())->method('findBy')->with(['subdomain' => 'sub'])->willReturn(1);

        $this->entityManager->expects(self::never())->method('persist');
        $this->entityManager->expects(self::never())->method('flush');
        $this->bindFileService->expects(self::never())->method('registerSubdomain')->with('sub');
        $subdomainService->expects(self::never())->method('activateSubdomain');

        $this->expectException(\RuntimeException::class);
        $this->expectExceptionMessage('This subdomain is already registered');

        $subdomainService->addNewSubdomain($organization, 'sub');
    }

    public function testAddNewSubdomainAndActivate(): void
    {
        $subdomainService = $this->makeSubdomainServiceMockFor('addNewSubdomain');

        $organization = $this->getMockBuilder(Organization::class)->disableOriginalConstructor()->getMock();

        $subdomainService->expects(self::once())->method('isValidSubdomain')->with('sub')->willReturn(true);
        $subdomainService->expects(self::once())->method('canRegisterNewSubdomain')->with($organization)->willReturn(true);
        $this->subdomainRepository->expects(self::once())->method('findBy')->with(['subdomain' => 'sub'])->willReturn(0);

        $subdomainService->expects(self::once())->method('activateSubdomain');

        $subdomainService->addNewSubdomain($organization, 'sub', true);
    }

    public function testActivateSubdomain(): void {
        $subdomainService = $this->makeSubdomainServiceMockFor('activateSubdomain');

        $organization = $this->getMockBuilder(Organization::class)->disableOriginalConstructor()->getMock();

        $initialSubdomain = $this->getMockBuilder(Subdomain::class)->getMock();
        $initialSubdomain->method('getId')->willReturn(1);
        $initialSubdomain->method('isActive')->willReturn(false);

        $activatedSubdomain = $this->getMockBuilder(Subdomain::class)->getMock();
        $activatedSubdomain->method('getId')->willReturn(1);
        $activatedSubdomain->method('isActive')->willReturn(true);
        $activatedSubdomain->method('getOrganization')->willReturn($organization);

        $subdomainService
            ->expects(self::once())
            ->method('setOrganizationActiveSubdomain')
            ->with($initialSubdomain)
            ->willReturn($activatedSubdomain);

        $subdomainService
            ->expects(self::once())
            ->method('renameAdminUserToMatchSubdomain')
            ->with($activatedSubdomain);

        $subdomainService
            ->expects(self::once())
            ->method('updateTypo3Website')
            ->with($organization);

        $subdomainService
            ->expects(self::once())
            ->method('sendConfirmationEmail')
            ->with($activatedSubdomain);

        $result = $subdomainService->activateSubdomain($initialSubdomain);

        $this->assertEquals($result, $activatedSubdomain);
    }

    public function testActivateSubdomainAlreadyActive(): void
    {
        $subdomainService = $this->makeSubdomainServiceMockFor('activateSubdomain');

        $subdomain = $this->getMockBuilder(Subdomain::class)->getMock();
        $subdomain->method('getId')->willReturn(1);
        $subdomain->method('isActive')->willReturn(true);

        $subdomainService->expects(self::never())->method('setOrganizationActiveSubdomain');
        $subdomainService->expects(self::never())->method('renameAdminUserToMatchSubdomain');
        $subdomainService->expects(self::never())->method('updateTypo3Website');
        $subdomainService->expects(self::never())->method('sendConfirmationEmail');


        $this->expectException(\RuntimeException::class);
        $this->expectExceptionMessage('The subdomain is already active');

        $subdomainService->activateSubdomain($subdomain);
    }

    public function testActivateSubdomainNotPersisted(): void
    {
        $subdomainService = $this->makeSubdomainServiceMockFor('activateSubdomain');

        $subdomain = $this->getMockBuilder(Subdomain::class)->getMock();
        $subdomain->method('getId')->willReturn(null);
        $subdomain->method('isActive')->willReturn(false);

        $subdomainService->expects(self::never())->method('setOrganizationActiveSubdomain');
        $subdomainService->expects(self::never())->method('renameAdminUserToMatchSubdomain');
        $subdomainService->expects(self::never())->method('updateTypo3Website');
        $subdomainService->expects(self::never())->method('sendConfirmationEmail');

        $this->expectException(\RuntimeException::class);
        $this->expectExceptionMessage('Can not activate a non-persisted subdomain');

        $subdomainService->activateSubdomain($subdomain);
    }

    public function testSetOrganizationActiveSubdomain(): void {
        $subdomainService = $this->makeSubdomainServiceMockFor('setOrganizationActiveSubdomain');

        $organization = $this->getMockBuilder(Organization::class)->disableOriginalConstructor()->getMock();

        $subdomain = $this->getMockBuilder(Subdomain::class)->getMock();
        $subdomain->method('getId')->willReturn(1);
        $subdomain->method('isActive')->willReturn(false);

        $otherSubdomain1 = $this->getMockBuilder(Subdomain::class)->getMock();
        $otherSubdomain1->method('getId')->willReturn(2);
        $otherSubdomain1->method('isActive')->willReturn(true);

        $otherSubdomain2 = $this->getMockBuilder(Subdomain::class)->getMock();
        $otherSubdomain2->method('getId')->willReturn(3);
        $otherSubdomain2->method('isActive')->willReturn(false);

        $organization->method('getSubdomains')->willReturn(new ArrayCollection([$otherSubdomain1, $otherSubdomain2]));
        $subdomain->method('getOrganization')->willReturn($organization);

        // The active subdomain is deactivated
        $otherSubdomain1->expects(self::once())->method('setActive')->with(false);

        // The inactive subdomain is not modified
        $otherSubdomain2->expects(self::never())->method('setActive');

        // The new subdomain is activated
        $subdomain->expects(self::once())->method('setActive')->with(true);

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

        $result = $subdomainService->setOrganizationActiveSubdomain($subdomain);

        $this->assertEquals($result, $subdomain);
    }

    public function testRenameAdminUserToMatchSubdomain(): void {
        $subdomainService = $this->makeSubdomainServiceMockFor('renameAdminUserToMatchSubdomain');

        $organization = $this->getMockBuilder(Organization::class)->getMock();
        $person = $this->getMockBuilder(Person::class)->getMock();
        $access = $this->getMockBuilder(Access::class)->getMock();
        $subdomain = $this->getMockBuilder(Subdomain::class)->getMock();

        $this->accessRepository
            ->method('findAdminAccess')
            ->with($organization)
            ->willReturn($access);

        $subdomain->method('getSubdomain')->willReturn('sub');
        $subdomain->method('getOrganization')->willReturn($organization);

        $access->method('getPerson')->willReturn($person);

        $person->expects(self::once())->method('setUsername')->with('adminsub');

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

        $subdomainService->renameAdminUserToMatchSubdomain($subdomain);
    }

    public function testUpdateTypo3Website(): void {
        $subdomainService = $this->makeSubdomainServiceMockFor('updateTypo3Website');

        $organization = $this->getMockBuilder(Organization::class)->getMock();
        $organization->method('getId')->willReturn(1);

        $this->messageBus
            ->expects(self::once())
            ->method('dispatch')
            ->with(self::isInstanceOf(Typo3UpdateCommand::class))
            ->willReturn(new Envelope(new Typo3UpdateCommand(1)));

        $subdomainService->updateTypo3Website($organization);
    }

    public function testGetMailModel(): void {
        $subdomainService = $this->makeSubdomainServiceMockFor('getMailModel');

        $access = $this->getMockBuilder(Access::class)->getMock();
        $access->method('getId')->willReturn(1);

        $organization = $this->getMockBuilder(Organization::class)->getMock();
        $organization->method('getId')->willReturn(1);

        $subdomain = $this->getMockBuilder(Subdomain::class)->disableOriginalConstructor()->getMock();
        $subdomain->method('getOrganization')->willReturn($organization);
        $subdomain->method('getId')->willReturn(1);

        $this->accessRepository
            ->method('findAdminAccess')
            ->with($organization)
            ->willReturn($access);

        $this->organizationUtils
            ->expects(self::once())
            ->method('getOrganizationWebsite')
            ->with($organization)
            ->willReturn('mysubdomain.opentalent.fr');

        $mailerModel = $subdomainService->getMailModel($subdomain);

        $this->assertInstanceOf(SubdomainChangeModel::class, $mailerModel);
        $this->assertEquals(1, $mailerModel->getSenderId());
        $this->assertEquals(1, $mailerModel->getOrganizationId());
        $this->assertEquals(1, $mailerModel->getSubdomainId());
        $this->assertEquals('mysubdomain.opentalent.fr', $mailerModel->getUrl());
    }

    public function testSendConfirmationEmail(): void {
        $subdomainService = $this->makeSubdomainServiceMockFor('sendConfirmationEmail');

        $subdomain = $this->getMockBuilder(Subdomain::class)->getMock();
        $subdomainChangeModel = $this->getMockBuilder(SubdomainChangeModel::class)->getMock();

        $subdomainService->method('getMailModel')->willReturn($subdomainChangeModel);

        $this->messageBus
            ->expects(self::once())
            ->method('dispatch')
            ->with(self::isInstanceOf(MailerCommand::class))
            ->willReturn(new Envelope(new MailerCommand($subdomainChangeModel)));

        $subdomainService->sendConfirmationEmail($subdomain);
    }
}
