<?php

declare(strict_types=1);

/*
 * This file is part of the Ferienpass package.
 *
 * (c) Richard Henkenjohann <richard@ferienpass.online>
 *
 * For more information visit the project website <https://ferienpass.online>
 * or the documentation under <https://docs.ferienpass.online>.
 */

namespace Ferienpass\CoreBundle\Repository;

use Doctrine\Bundle\DoctrineBundle\Repository\ServiceEntityRepository;
use Doctrine\Persistence\ManagerRegistry;
use Ferienpass\CoreBundle\Entity\User;

class UserRepository extends ServiceEntityRepository
{
    public function __construct(ManagerRegistry $registry)
    {
        parent::__construct($registry, User::class);
    }

    /**
     * Every user holding at least one admin role — i.e. the colleagues that
     * receive in-app activity notifications.
     *
     * @return array<int, User>
     */
    public function findAdmins(): array
    {
        $qb = $this->createQueryBuilder('u');
        $orX = $qb->expr()->orX();

        foreach (array_values(User::ADMIN_ROLES) as $i => $role) {
            // roles is a JSON array column; match the quoted, JSON-encoded role.
            $orX->add($qb->expr()->like('u.roles', ':role'.$i));
            $qb->setParameter('role'.$i, '%"'.$role.'"%');
        }

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