<?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 readonly SitemapRenderer $renderer,
        private readonly RouterInterface $router,
        private readonly ManagerRegistry $doctrine,
        private readonly SiteContextHelper $contextHelper,
    ) {
    }

    public function index(Request $request, array $robotsBlocks = []): Response
    {
        if (empty($robotsBlocks)) {
            $robotsBlocks = [
                [
                    'user_agents' => ['*'],
                    'rules' => [
                        'Disallow: ',
                    ],
                ],
            ];
        }

        $parts = [];
        foreach ($robotsBlocks as $block) {
            $userAgents = $block['user_agents'] ?? ['*'];
            $rules = $block['rules'] ?? [];

            foreach ($userAgents as $userAgent) {
                $parts[] = 'User-agent: '.$userAgent;
            }
            foreach ($rules as $rule) {
                $parts[] = $rule;
            }
            $parts[] = '';
        }

        $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', Response::HTTP_NOT_FOUND);
        }

        // /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, Response::HTTP_OK, ['content-type' => 'text/plain;charset=UTF-8']);
    }
}
