<?php

namespace AutoAdmin\Bundle\Content\Site;

use AutoAdmin\Bundle\Content\Entity\Domain;
use Doctrine\ORM\EntityManagerInterface;
use RuntimeException;

class HostLocaleFinder
{
    public function __construct(
        protected EntityManagerInterface $em,
    ) {
    }

    /**
     * Mostly used for untranslated sites, or for index path ("/") of internationalized sites
     *
     * First site-declaration priority concept (race concurrency / cloaking consequences):
     * - ideally we want a domain to be limited to one site
     * - if a domain is used for two different sites, the first to declare it will be prioritized
     * - it will affect what locales can be matched because those will be restricted by the first site configuration
     * - we need to proceed as-is and cloak other domains because we need a site before defining current locale
     * depending on the kind of routing setup to be able to bootstrap SiteContext
     * - sitemaps problems are also impacting duplicated domains
     *
     */
    public function findDefaultLocale(string $host): ?string
    {
        $domainRepo = $this->em->getRepository(Domain::class);
        /** @var Domain[] $domains */
        $domains = $domainRepo->findBy(['domain' => $host,]);

        foreach ($domains as $domain) {
            $locales = $domain->getLocales();
            foreach ($locales as $locale) {
                if ($locale) {
                    return $locale->getCode();
                }
            }
        }

        throw new RuntimeException('Could not match any default locale or no domain matching "'.$host.'".');
    }
}
