<?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\Workflow\EntityWorkflowStep;
use Chill\MainBundle\Entity\Workflow\EntityWorkflowStepHold;
use Doctrine\Bundle\DoctrineBundle\Repository\ServiceEntityRepository;
use Doctrine\ORM\NonUniqueResultException;
use Doctrine\ORM\NoResultException;
use Doctrine\Persistence\ManagerRegistry;

/**
 * @template-extends ServiceEntityRepository<EntityWorkflowStepHold>
 */
class EntityWorkflowStepHoldRepository extends ServiceEntityRepository
{
    public function __construct(ManagerRegistry $registry)
    {
        parent::__construct($registry, EntityWorkflowStepHold::class);
    }

    /**
     * Find an EntityWorkflowStepHold by its ID.
     */
    public function findById(int $id): ?EntityWorkflowStepHold
    {
        return $this->find($id);
    }

    /**
     * Find all EntityWorkflowStepHold records.
     *
     * @return EntityWorkflowStepHold[]
     */
    public function findAllHolds(): array
    {
        return $this->findAll();
    }

    /**
     * Find EntityWorkflowStepHold by a specific step.
     *
     * @return EntityWorkflowStepHold[]
     */
    public function findByStep(EntityWorkflowStep $step): array
    {
        return $this->findBy(['step' => $step]);
    }

    /**
     * Find a single EntityWorkflowStepHold by step and user.
     *
     * @throws NonUniqueResultException
     */
    public function findOneByStepAndUser(EntityWorkflowStep $step, User $user): ?EntityWorkflowStepHold
    {
        try {
            return $this->createQueryBuilder('e')
                ->andWhere('e.step = :step')
                ->andWhere('e.byUser = :user')
                ->setParameter('step', $step)
                ->setParameter('user', $user)
                ->getQuery()
                ->getSingleResult();
        } catch (NoResultException) {
            return null;
        }
    }
}
