<?php

declare(strict_types=1);

namespace App\Repository\Organization;

use App\Entity\Organization\Organization;
use App\Entity\Organization\Subdomain;
use Doctrine\Bundle\DoctrineBundle\Repository\ServiceEntityRepository;
use Doctrine\Persistence\ManagerRegistry;

/**
 * @method Subdomain|null find($id, $lockMode = null, $lockVersion = null)
 * @method Subdomain|null findOneBy(mixed[] $criteria, mixed[] $orderBy = null)
 * @method Subdomain[]    findAll()
 * @method Subdomain[]    findBy(mixed[] $criteria, mixed[] $orderBy = null, $limit = null, $offset = null)
 */
class SubdomainRepository extends ServiceEntityRepository
{
    public function __construct(ManagerRegistry $registry)
    {
        parent::__construct($registry, Subdomain::class);
    }

    /**
     * Returns the current active subdomain of an organization, or null if there are'nt any.
     */
    public function getActiveSubdomainOf(Organization $organization): ?Subdomain
    {
        $qb = $this->createQueryBuilder('subdomain');

        return $qb
                ->where('subdomain.organization = :organization')
                ->andWhere($qb->expr()->eq('subdomain.active', true))
                ->setParameter('organization', $organization)
                ->getQuery()
                ->getOneOrNullResult();
    }
}
