<?php

declare(strict_types=1);

namespace App\Tests\DoctrineExtension\Access;

use App\Doctrine\Access\CurrentUserPersonalizedListExtension;
use App\Entity\Access\PersonalizedList;
use App\Tests\Unit\Doctrine\ExtensionTestCase;
use Symfony\Component\Security\Core\User\UserInterface;

class CurrentUserPersonalizedListExtensionTest extends ExtensionTestCase
{
    private $extension;

    protected function setUp(): void
    {
        parent::setUp();
        $this->extension = new CurrentUserPersonalizedListExtension($this->security);
    }

    public function testSupportsReturnsTrueForPersonalizedListClass()
    {
        $this->assertTrue($this->extension->supports(PersonalizedList::class, null));
    }

    public function testSupportsReturnsFalseForOtherClasses()
    {
        $this->assertFalse($this->extension->supports('OtherClass', null));
    }

    public function testAddWhere()
    {
        $user = $this->createMock(UserInterface::class);
        $this->security->method('getUser')->willReturn($user);
        $this->queryBuilder->method('getRootAliases')->willReturn(['a']);
        $this->queryBuilder->expects($this->once())
            ->method('andWhere')
            ->with('a.access = :current_access')
            ->willReturn($this->queryBuilder);

        $this->queryBuilder->expects($this->once())
            ->method('setParameter')
            ->with('current_access', $user)
            ->willReturn($this->queryBuilder);

        $this->invokeAddWhere($this->extension, $this->queryBuilder, PersonalizedList::class, null);
    }

    public function testAddWhereWithNullUser()
    {
        $this->security->method('getUser')->willReturn(null);
        $this->queryBuilder->method('getRootAliases')->willReturn(['a']);
        $this->queryBuilder->expects($this->once())
            ->method('andWhere')
            ->with('a.access = :current_access')
            ->willReturn($this->queryBuilder);

        $this->queryBuilder->expects($this->once())
            ->method('setParameter')
            ->with('current_access', null)
            ->willReturn($this->queryBuilder);

        $this->invokeAddWhere($this->extension, $this->queryBuilder, PersonalizedList::class, null);
    }

    public function testAddWhereWithNoRootAlias()
    {
        $user = $this->createMock(UserInterface::class);
        $this->security->method('getUser')->willReturn($user);
        $this->queryBuilder->method('getRootAliases')->willReturn([]);

        $this->expectException(\LogicException::class);
        $this->expectExceptionMessage('No root alias defined.');

        $this->invokeAddWhere($this->extension, $this->queryBuilder, PersonalizedList::class, null);
    }
}
