<?php

declare(strict_types=1);

/*
 * This file is part of the Serenity package.
 *
 * (c) CP Creation <web@cpcreation.fr>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

namespace Serenity\AuthBundle\Doctrine\Repository;

use Doctrine\Persistence\ManagerRegistry;
use Serenity\AuthBundle\Domain\User\Model\User;
use Serenity\CoreBundle\Shared\Doctrine\Repository\BaseRepository;

final class UserRepository extends BaseRepository implements UserRepositoryInterface
{
    private const string ENTITY_CLASS = User::class;
    private const string ALIAS = 'user';

    public function __construct(ManagerRegistry $registry)
    {
        parent::__construct($registry, self::ENTITY_CLASS);
    }

    public function findOne(string $identifier, ?string $role = null): ?User
    {
        $qb = $this->createQueryBuilder(self::ALIAS)
            ->andWhere(self::ALIAS.'.email.value = :email')
            ->setMaxResults(1)
            ->setParameter('email', $identifier);

        if ($role) {
            $qb->andWhere('JSONB_CONTAINS(user.roles, :role) = true')
                ->setParameter('role', $role);
        }

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