<?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 updates an existing organization's website
 * with the latest data from the Opentalent DB
 *
 * @package Opentalent\OtAdmin\Command
 */
class UpdateSiteCommand 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:site:update")
            ->setDescription("Update an organization website")
            ->setHelp("This CLI command update an existing organization's website
                            with the latest data from the Opentalent DB")
            ->addOption(
                'all',
                null,
                InputOption::VALUE_NONE,
                "Update all of the organization websites"
            )
            ->addArgument(
                'organization-id',
                InputArgument::OPTIONAL,
                "The organization's id in the opentalent DB"
            )
            ->addOption(
                'delete',
                null,
                InputOption::VALUE_NONE,
                "Performs a soft deletion of the websites when the organization does not exist anymore " .
                "in the Opentalent DB. (This only applies if the --all option is used)"
            );
    }

    /**
     * -- 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)
    {
        $org_id = $input->getArgument('organization-id');
        $all = $input->getOption('all');
        $delete = $input->getOption('delete');

        if ($all && $org_id) {
            throw new \InvalidArgumentException("You can not pass both an organization id and the --all option");
        }
        if (!$all && !$org_id) {
            throw new \InvalidArgumentException("You shall either pass an organization id or use the --all option");
        }
        if (!$all && $delete) {
            throw new \InvalidArgumentException("The delete option only applies when the --all option is passed");
        }

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

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

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

            foreach ($sites as $site) {
                $org_id = $site['organization_id'];
                try {
                    $this->siteController->updateSiteAction($org_id);
                } catch (NoSuchOrganizationException $e) {
                    if ($delete) {
                        $this->siteController->deleteSiteAction($org_id);
                    } else {
                        throw $e;
                    }
                } catch (\Throwable $e) {
                    $io->error('Organization Id: ' . $org_id . ' - ' . $e->getMessage());
                }
                $io->progressAdvance(1);
            }
            $io->progressFinish();

            $io->success(sprintf("The websites have all been updated"));
        } else {
            $rootUid = $this->siteController->updateSiteAction($org_id);
            $io->success(sprintf("The website with root uid " . $rootUid . " has been updated"));
        }
        return 0;
    }
}
