<?php

namespace AutoAdmin\Bundle\Seo\Command;

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(
            'siteSlug',
            InputArgument::OPTIONAL,
            'Site slug (e.g. aaaa or aaaa,bbbb for multiple sites) default is all enabled sites',
            '*',
        );
    }

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

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

        $siteSlug = $input->getArgument('siteSlug');
        if ($siteSlug === '*') {
            $sites = $siteRepo->findBy(['enabled' => true,]);
        } else {
            $siteSlugs = explode(',', $siteSlug);
            $sites = [];
            foreach ($siteSlugs as $slug) {
                $site = $siteRepo->findOneBy(['enabled' => true, 'slug' => $slug]);
                if (empty($site)) {
                    $io->error('Could not find site matching given domain/slug ('.$slug.')');

                    return Command::FAILURE;
                }
                $sites[] = $site;
            }
        }

        $globalSiteConfigs = [];
        foreach ($sites as $site) {
            $siteConfigs = $this->contextHelper->getSiteConfigs($site);
            $globalSiteConfigs = [
                ...$globalSiteConfigs,
                ...$siteConfigs,
            ];
        }

//        dump($globalSiteConfigs);

        foreach ($globalSiteConfigs 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;
    }
}
