<?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();

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

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

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