<?php

declare(strict_types=1);

namespace App\Tests\Unit\Doctrine\Network;

use App\Doctrine\Network\CurrentNetworkOrganizationExtension;
use App\Entity\Access\Access;
use App\Entity\Network\NetworkOrganization;
use App\Tests\Unit\Doctrine\ExtensionTestCase;

class CurrentNetworkOrganizationExtensionTest extends ExtensionTestCase
{
    private $extension;

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

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

    public function testSupportsReturnsFalseForOtherClasses()
    {
        $classes = ['OtherClass', Access::class];

        foreach ($classes as $class) {
            $this->assertFalse($this->extension->supports($class, null));
        }
    }

    public function testAddWhere()
    {
        $this->user->method('getOrganization')->willReturn($this->organization);
        $this->security->method('getUser')->willReturn($this->user);
        $this->queryBuilder->method('getRootAliases')->willReturn(['o']);

        $this->queryBuilder->expects($this->once())
            ->method('andWhere')
            ->with('o.organization = :organization')
            ->willReturn($this->queryBuilder);

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

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

    public function testAddWhereWithNullUser()
    {
        $this->security->method('getUser')->willReturn(null);
        $this->queryBuilder->method('getRootAliases')->willReturn(['o']);
        $this->queryBuilder->expects($this->never())
            ->method('andWhere');
        $this->queryBuilder->expects($this->never())
            ->method('setParameter');

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

    public function testAddWhereWithNullOrganization()
    {
        $this->user->method('getOrganization')->willReturn(null);
        $this->security->method('getUser')->willReturn($this->user);
        $this->queryBuilder->method('getRootAliases')->willReturn(['o']);
        $this->queryBuilder->expects($this->never())
            ->method('andWhere');
        $this->queryBuilder->expects($this->never())
            ->method('setParameter');

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