<?php


namespace AutoAdmin\Bundle\Seo\Controller;


use AutoAdmin\Bundle\Content\Entity\Domain;
use AutoAdmin\Bundle\Content\Site\SiteContextHelper;
use AutoAdmin\Bundle\Seo\Sitemap\SitemapRenderer;
use Doctrine\Persistence\ManagerRegistry;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\Routing\RouterInterface;

class RobotsController
{
    public function __construct(
        private SitemapRenderer $renderer,
        private RouterInterface $router,
        private ManagerRegistry $doctrine,
        private SiteContextHelper $contextHelper,
    ) {
    }


    public function index(Request $request): Response
    {
        $parts = [
            'User-agent: *',
            'Disallow: ',
        ];

        $host = $request->getHost();
        $domainRepo = $this->doctrine->getRepository(Domain::class);
        /** @var Domain[] $domains */
        $domain = $domainRepo->findOneBy(['domain' => $host,]);

        if (!$domain) {
            return new Response('No domain found', 404);
        }

        // /robots.txt in on index, so redirect to all localized sitemaps
        $siteConfigs = $this->contextHelper->getSiteConfigs($domain->getSite());
        foreach ($siteConfigs as $siteConfig) {
            if ($siteConfig->getDomain()->getDomain() !== $host) {
                // multi lang based on domain, only serve current domain
                continue;
            }
            $this->contextHelper->loadSiteConfig($siteConfig);
            $domainStr = $siteConfig->getDomain()->getDomain();
            $localeCode = $siteConfig->getLocale()->getCode();

            $routerLocaleParameter = [];
            $locales = $this->contextHelper->getDomain()->getLocales();
            $routeName = 'aa_seo_sitemap_no_locale';
            if ($locales->count() > 1) {
                $routeName = 'aa_seo_sitemap';
                $routerLocaleParameter = ['_locale' => $localeCode];
            }

            $pattern = 'Sitemap: https://'.$domainStr.'%s';
            foreach ($this->renderer->getSections() as $section) {
                $routerParameters = array_merge($routerLocaleParameter, ['section' => $section]);
                $subSitemapUrl = $this->router->generate($routeName, $routerParameters);
                $parts[] = sprintf($pattern, $subSitemapUrl);
            }
        }

        $text = implode("\n", $parts)."\n";

        return new Response($text, 200, ['content-type' => 'text/plain;charset=UTF-8']);
    }
}
