<?php

namespace AutoAdmin\Bundle\Seo\Command;

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\Console\Command\Command;
use Symfony\Component\Console\Input\InputArgument;
use Symfony\Component\Console\Input\InputInterface;
use Symfony\Component\Console\Output\OutputInterface;
use Symfony\Component\Console\Style\SymfonyStyle;

class SitemapCacheCommand extends Command
{
    protected static $defaultName = 'aa:seo:sitemap-cache';

    private SitemapRenderer $renderer;
    private ManagerRegistry $doctrine;
    private SiteContextHelper $siteContextHelper;

    public function __construct(
        SitemapRenderer $renderer,
        ManagerRegistry $doctrine,
        SiteContextHelper $siteContextHelper,
        string $name = null
    ) {
        parent::__construct($name);

        $this->renderer = $renderer;
        $this->doctrine = $doctrine;
        $this->siteContextHelper = $siteContextHelper;
    }

    protected function configure()
    {
        $this->setDescription('Force reload cache of sitemaps.');
        $this->addArgument('host', InputArgument::OPTIONAL, 'Host (e.g. domain.fr)');
        $this->addOption('scheme', null, InputArgument::OPTIONAL, 'Scheme (e.g. http or https)', 'https');
    }

    protected function execute(InputInterface $input, OutputInterface $output): int
    {
        $io = new SymfonyStyle($input, $output);

        $host = $input->getArgument('host');
        $domains = $this->doctrine->getRepository(Domain::class)->findAll();
        if ($host) {
            $domain = $this->doctrine->getRepository(Domain::class)->findOneBy(['domain' => $host]);
            if ($domain === null) {
                $io->error(sprintf('Domain "%s" not found.', $host));

                return self::FAILURE;
            }

            $domains = [$domain];
        }

        foreach ($domains as $domain) {
            $site = $domain->getSite();
            $io->writeln(sprintf('--- Reloading sitemap cache of "%s"', $domain->getDomain()));
            $this->siteContextHelper->loadSiteAndDefaultLocale($site);
            $hostAndScheme = sprintf('%s://%s', $input->getOption('scheme'), $domain->getDomain());

            foreach ($this->renderer->getSections() as $section) {
                $io->writeln(sprintf('Reloading cache for section "%s"...', $section));

                $this->renderer->render($hostAndScheme, $section, true);
            }
        }

        $io->success('Sitemaps cache reloaded.');

        return self::SUCCESS;
    }
}
