<?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\Workflow;

use Chill\MainBundle\Entity\User;
use Chill\MainBundle\Entity\UserGroup;
use Chill\MainBundle\Entity\Workflow\EntityWorkflowStep;
use Doctrine\ORM\EntityManagerInterface;
use Doctrine\ORM\EntityRepository;
use Doctrine\ORM\QueryBuilder;
use Doctrine\Persistence\ObjectRepository;

readonly class EntityWorkflowStepRepository implements ObjectRepository
{
    private EntityRepository $repository;

    public function __construct(EntityManagerInterface $entityManager)
    {
        $this->repository = $entityManager->getRepository(EntityWorkflowStep::class);
    }

    public function countUnreadByUser(User $user, ?array $orderBy = null, $limit = null, $offset = null): int
    {
        $qb = $this->buildQueryByUser($user)->select('count(e)');

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

    public function find($id): ?EntityWorkflowStep
    {
        return $this->repository->find($id);
    }

    public function findAll(): array
    {
        return $this->repository->findAll();
    }

    public function findBy(array $criteria, ?array $orderBy = null, $limit = null, $offset = null): array
    {
        return $this->repository->findBy($criteria, $orderBy, $limit, $offset);
    }

    public function findOneBy(array $criteria): ?EntityWorkflowStep
    {
        return $this->repository->findOneBy($criteria);
    }

    public function getClassName()
    {
        return EntityWorkflowStep::class;
    }

    private function buildQueryByUser(User $user): QueryBuilder
    {
        $qb = $this->repository->createQueryBuilder('e');

        $qb->where(
            $qb->expr()->andX(
                $qb->expr()->orX(
                    $qb->expr()->isMemberOf(':user', 'e.destUser'),
                    $qb->expr()->isMemberOf(':user', 'e.destUserByAccessKey'),
                    $qb->expr()->exists(sprintf('SELECT 1 FROM %s ug WHERE ug MEMBER OF e.destUserGroups AND :user MEMBER OF ug.users', UserGroup::class))
                ),
                $qb->expr()->isNull('e.transitionAt'),
                $qb->expr()->eq('e.isFinal', ':bool'),
            )
        );

        $qb->setParameter('user', $user);
        $qb->setParameter('bool', false);

        return $qb;
    }
}
