<?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\ThirdPartyBundle\Repository;

use Chill\MainBundle\Security\Authorization\AuthorizationHelper;
use Doctrine\ORM\QueryBuilder;
use Symfony\Component\Security\Core\Security;

final readonly class ThirdPartyACLAwareRepository implements ThirdPartyACLAwareRepositoryInterface
{
    public function __construct(private Security $security, private AuthorizationHelper $authorizationHelper, private ThirdPartyRepository $thirdPartyRepository) {}

    public function buildQuery(?string $filterString = null): QueryBuilder
    {
        $qb = $this->thirdPartyRepository->createQueryBuilder('tp');

        $qb->leftJoin('tp.parent', 'parent')
            ->andWhere($qb->expr()->andX(
                'tp.active = \'TRUE\'',
                $qb->expr()->orX($qb->expr()->isNull('parent'), 'parent.active = \'TRUE\'')
            ));

        if (null !== $filterString) {
            $qb->andWhere($qb->expr()->like('tp.canonicalized', 'LOWER(UNACCENT(:filterString))'))
                ->setParameter('filterString', '%'.$filterString.'%');
        }

        return $qb;
    }

    public function countThirdParties(
        string $role,
        ?string $filterString,
    ): int {
        $qb = $this->buildQuery($filterString);
        $qb->select('count(tp)');

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

    public function listThirdParties(
        string $role,
        ?string $filterString,
        ?array $orderBy = [],
        ?int $limit = null,
        ?int $offset = null,
    ): array {
        $qb = $this->buildQuery($filterString);

        foreach ($orderBy as $sort => $direction) {
            $qb->addOrderBy('tp.'.$sort, $direction);
        }

        $qb->setFirstResult($offset)
            ->setMaxResults($limit);

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