<?php

declare(strict_types=1);

namespace Ferienpass\CoreBundle\Tests\Facade;

use Doctrine\DBAL\Connection;
use Doctrine\ORM\EntityManagerInterface;
use Doctrine\ORM\QueryBuilder;
use Ferienpass\CoreBundle\Facade\EraseDataFacade;
use Ferienpass\CoreBundle\Repository\ParticipantRepositoryInterface;
use Ferienpass\CoreBundle\Settings\SystemSettingsManager;
use PHPUnit\Framework\TestCase;

class EraseDataFacadeTest extends TestCase
{
    public function testExpiredParticipantsWithNullPeriod(): void
    {
        $connection = $this->createMock(Connection::class);
        $participants = $this->createMock(ParticipantRepositoryInterface::class);
        $doctrine = $this->createMock(EntityManagerInterface::class);
        $systemSettingsManager = $this->createMock(SystemSettingsManager::class);

        $systemSettingsManager->expects($this->once())
            ->method('getEraseDataPeriod')
            ->willReturn(null);

        $facade = new EraseDataFacade($connection, $participants, $doctrine, $systemSettingsManager, 'App\Entity\Participant');

        $this->assertSame([], $facade->expiredParticipants());
    }

    public function testExpiredParticipantsWithValidPeriod(): void
    {
        $connection = $this->createMock(Connection::class);
        $participants = $this->createMock(ParticipantRepositoryInterface::class);
        $doctrine = $this->createMock(EntityManagerInterface::class);
        $systemSettingsManager = $this->createMock(SystemSettingsManager::class);

        $systemSettingsManager->expects($this->once())
            ->method('getEraseDataPeriod')
            ->willReturn('30 days');

        $qb = $this->createMock(QueryBuilder::class);
        $expr = new \Doctrine\ORM\Query\Expr();

        $doctrine->method('createQueryBuilder')->willReturn($qb);
        $qb->method('select')->willReturn($qb);
        $qb->method('from')->willReturn($qb);
        $qb->method('leftJoin')->willReturn($qb);
        $qb->method('innerJoin')->willReturn($qb);
        $qb->method('groupBy')->willReturn($qb);
        $qb->method('setParameter')->willReturn($qb);
        $qb->method('where')->willReturn($qb);
        $qb->method('orderBy')->willReturn($qb);
        $qb->method('expr')->willReturn($expr);

        $query = $this->getMockBuilder(\Doctrine\ORM\Query::class)
            ->disableOriginalConstructor()
            ->getMock();
        $qb->method('getQuery')->willReturn($query);
        $query->method('getScalarResult')->willReturn([]);

        $facade = new EraseDataFacade($connection, $participants, $doctrine, $systemSettingsManager, 'App\Entity\Participant');

        $this->assertSame([], $facade->expiredParticipants());
    }
}
