<?php

namespace Opentalent\OtAdmin\Command;


use Opentalent\OtAdmin\Controller\SiteController;
use Opentalent\OtCore\Exception\NoSuchOrganizationException;
use Symfony\Component\Console\Command\Command;
use Symfony\Component\Console\Input\InputArgument;
use Symfony\Component\Console\Input\InputInterface;
use Symfony\Component\Console\Input\InputOption;
use Symfony\Component\Console\Output\OutputInterface;
use Symfony\Component\Console\Style\SymfonyStyle;
use TYPO3\CMS\Core\Database\ConnectionPool;
use TYPO3\CMS\Core\Utility\GeneralUtility;
use TYPO3\CMS\Extbase\Object\ObjectManager;

/**
 * This CLI command loop over the ot_websites and delete the ones whom organization doesn't exist anymore
 *
 * @package Opentalent\OtAdmin\Command
 */
class ClearObsoleteWebsitesSiteCommand extends Command
{
    public function __construct(
        private readonly SiteController $siteController,
        private readonly ConnectionPool $connectionPool
    ) {
        parent::__construct();
    }

    /**
     * -- This method is expected by Typo3, do not rename ou remove --
     *
     * Allows to configure the command.
     * Allows to add a description, a help text, and / or define arguments.
     *
     */
    protected function configure()
    {
        $this
            ->setName("ot:clear-obsoletes-websites")
            ->setDescription("Delete obsolete websites")
            ->setHelp(" This CLI command loop over the ot_websites and delete 
                        the ones whom organization doesn't exist anymore")
            ->addOption(
                'preview',
                'p',
                InputOption::VALUE_NONE,
                "Only preview, perform no deletion"
            );
    }

    /**
     * -- This method is expected by Typo3, do not rename ou remove --
     *
     * @param InputInterface $input
     * @param OutputInterface $output
     * @return int
     * @throws NoSuchOrganizationException
     * @throws \Doctrine\DBAL\ConnectionException
     * @throws \Doctrine\DBAL\DBALException
     * @throws \Opentalent\OtCore\Exception\InvalidWebsiteConfigurationException
     * @throws \Opentalent\OtCore\Exception\NoSuchRecordException
     * @throws \Opentalent\OtCore\Exception\NoSuchWebsiteException
     * @throws \TYPO3\CMS\Extbase\Object\Exception
     * @throws \Throwable
     */
    protected function execute(InputInterface $input, OutputInterface $output)
    {
        $preview = $input->getOption('preview');

        $io = new SymfonyStyle($input, $output);

        $queryBuilder = $this->connectionPool->getQueryBuilderForTable('ot_websites');
        $sites = $queryBuilder
            ->select('organization_id')
            ->from('ot_websites')
            ->where($queryBuilder->expr()->eq('deleted', 0))
            ->execute()
            ->fetchAll();

        $io->progressStart(count($sites));

        $n = 0;
        foreach ($sites as $site) {
            try {
                $this->siteController->fetchOrganization($site['organization_id']);
            } catch (NoSuchOrganizationException $e) {
                $n++;
                if ($preview) {
                    $io->info('Site ' . $site['uid'] . ' to delete : ' . $site['organization_id'] . ' [' . $site['organization_name'] . ']');
                    continue;
                }
                $this->siteController->deleteSiteAction($site['organization_id']);
                $io->info('Website ' . $site['uid'] . ' deleted : ' . $site['organization_id'] . ' [' . $site['organization_name'] . ']');
            }
            /** @noinspection DisconnectedForeachInstructionInspection */
            $io->progressAdvance();
        }
        $io->progressFinish();

        if (!$preview) {
            $io->success(sprintf($n . " websites have been successfully deleted"));
        } else {
            $io->success(sprintf("Preview ended -- " . $n . ' websites would be deleted'));
        }

        return Command::SUCCESS;
    }
}
