<?php

declare(strict_types=1);

/*
 * Chill is a software for social workers
 *
 * For the full copyright and license information, please view
 * the LICENSE file that was distributed with this source code.
 */

namespace Chill\MainBundle\Repository;

use Chill\MainBundle\Entity\Center;
use Chill\MainBundle\Entity\Scope;
use Chill\MainBundle\Entity\User;
use Chill\MainBundle\Security\ParentRoleHelper;
use Doctrine\ORM\EntityManagerInterface;

class UserACLAwareRepository implements UserACLAwareRepositoryInterface
{
    public function __construct(private readonly ParentRoleHelper $parentRoleHelper, private readonly EntityManagerInterface $em) {}

    public function findUsersByReachedACL(string $role, $center, $scope = null, bool $onlyEnabled = true): array
    {
        $parents = $this->parentRoleHelper->getParentRoles($role);
        $parents[] = $role;

        $qb = $this->em->createQueryBuilder();

        $qb
            ->select('u')
            ->from(User::class, 'u')
            ->join('u.groupCenters', 'gc')
            ->join('gc.permissionsGroup', 'pg')
            ->join('pg.roleScopes', 'rs')
            ->where($qb->expr()->in('rs.role', $parents));

        if ($onlyEnabled) {
            $qb->andWhere($qb->expr()->eq('u.enabled', "'TRUE'"));
        }

        if (null !== $center) {
            $centers = $center instanceof Center ? [$center] : $center;
            $qb
                ->andWhere($qb->expr()->in('gc.center', ':centers'))
                ->setParameter('centers', $centers);
        }

        if (null !== $scope) {
            $scopes = $scope instanceof Scope ? [$scope] : $scope;
            $qb
                ->andWhere($qb->expr()->in('rs.scope', ':scopes'))
                ->setParameter('scopes', $scopes);
        }

        return $qb->getQuery()->getResult();
    }
}
