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

/**
 * @extends ServiceEntityRepository<TenantDomain>
 */
class TenantDomainRepository extends ServiceEntityRepository
{
    public function __construct(ManagerRegistry $registry)
    {
        parent::__construct($registry, TenantDomain::class);
    }

    /**
     * The domain a request host addresses, or null when no enabled tenant
     * claims it. Callers must treat null as "reject the request", never as
     * "fall back to some default tenant".
     */
    public function findOneByHost(string $host): ?TenantDomain
    {
        $host = TenantDomain::normalizeHost($host);
        if ('' === $host) {
            return null;
        }

        return $this->createQueryBuilder('d')
            ->innerJoin('d.tenant', 't')
            ->addSelect('t')
            ->andWhere('d.host = :host')
            ->andWhere('t.disabled = false')
            ->setParameter('host', $host)
            ->setMaxResults(1)
            ->getQuery()
            ->getOneOrNullResult()
        ;
    }
}
