<?php

namespace AutoAdmin\Bundle\Seo\Command;

use AutoAdmin\Bundle\Content\Entity\Domain;
use AutoAdmin\Bundle\Content\Entity\Site;
use AutoAdmin\Bundle\Content\Site\SiteContextHelper;
use AutoAdmin\Bundle\Seo\Cache\SitemapCacheHandler;
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';

    public function __construct(
        protected SitemapRenderer $renderer,
        protected ManagerRegistry $doctrine,
        protected SiteContextHelper $contextHelper,
        protected SitemapCacheHandler $sitemapCacheHandler,
        string $name = null
    ) {
        parent::__construct($name);
    }

    protected function configure()
    {
        $this->setDescription('Force reload cache of sitemaps.');

        // use either host or site slug
        $this->addArgument('domainOrSiteSlug', InputArgument::OPTIONAL, 'Host (e.g. domain.fr)');
    }

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

        $domainRepo = $this->doctrine->getRepository(Domain::class);
        $siteRepo = $this->doctrine->getRepository(Site::class);


        $domainOrSiteSlug = $input->getArgument('domainOrSiteSlug');

        $domain = $domainRepo->findOneBy(['domain' => $domainOrSiteSlug]);
        $site = $siteRepo->findOneBy(['slug' => $domainOrSiteSlug]);

        if(empty($domain) && empty($site)) {
            $io->error('Could not find site matching given domain/slug ('.$domainOrSiteSlug.')');

            return Command::FAILURE;
        }

        if(!empty($domain)) {
            $siteConfigs = $this->contextHelper->getSiteConfigs($domain->getSite());
        } elseif($site) {
            $siteConfigs = $this->contextHelper->getSiteConfigs($site);
        } else {
            // no option given, loop over all sites
            $siteConfigs = $this->contextHelper->getAllSiteConfigs();
        }

        foreach ($siteConfigs as $siteConfig) {
            $this->contextHelper->loadSiteConfig($siteConfig);
            $io->writeln('Handling: '.$siteConfig->getSite()->getSlug().' with locale: '.$siteConfig->getLocale());

            $this->sitemapCacheHandler->saveSiteValue();
        }

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

        return self::SUCCESS;
    }
}
