<?php

namespace AutoAdmin\Bundle\Content\Translation;

use AutoAdmin\Bundle\Content\Site\SiteContextHelper;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\RequestStack;

class LocaleResolver
{
    private ?Request $request;

    public function __construct(
        RequestStack $requestStack,
        private SiteContextHelper $contextHelper,
    ) {
        $this->request = $requestStack->getMainRequest();
    }

    public function resolveLocale(string $locale = null)
    {
        $resolved =
            $locale ??
            // admin prio
            $this->request?->get('_admin_locale') ??
            // finally take locale from SiteContext
            $this->contextHelper->getLocale()?->getCode() ??
            // for now, disable request locale usage, often not matching our site-locale matrix
//            $this->requestStack->getMainRequest()?->getLocale() ??
            throw new \Exception('No locale resolved.');

        return $resolved;
    }
}