<?php

namespace AutoAdmin\Bundle\Admin\Command\Admin;

use AutoAdmin\Bundle\Admin\Model\AdministratorInterface;
use AutoAdmin\Bundle\Content\Entity\Site;
use Doctrine\Persistence\ManagerRegistry;
use Exception;
use Symfony\Component\Console\Attribute\AsCommand;
use Symfony\Component\Console\Command\Command;
use Symfony\Component\Console\Input\InputInterface;
use Symfony\Component\Console\Output\OutputInterface;
use Symfony\Component\Console\Question\Question;

#[AsCommand(name: 'aa:admin:allow-administrator')]
class AllowAdministratorCommand extends Command
{
    private ManagerRegistry $doctrine;

    public function __construct(ManagerRegistry $doctrine)
    {
        $this->doctrine = $doctrine;

        parent::__construct();
    }

    protected function configure(): void
    {
        $this->setDescription('Allow an administrator to administrate a specific site.');
    }

    protected function execute(InputInterface $input, OutputInterface $output): int
    {
        $helper = $this->getHelper('question');

        $em = $this->doctrine->getManager();

        try {
            $adminUsername = $helper->ask(
                $input,
                $output,
                new Question('Admin slug ?')
            );

            $siteSlug = $helper->ask(
                $input,
                $output,
                new Question('Website slug ?')
            );
            if (
                empty($adminUsername)
                || empty($siteSlug)
            ) {
                $output->writeln('<error>' . 'You must provide all options. Aborting.' . '</error>');

                return self::FAILURE;
            }

            /** @var Site $site */
            $site = $em->getRepository(Site::class)->findOneBy(['slug' => $siteSlug,]);
            /** @var AdministratorInterface $admin */
            $admin = $em->getRepository(AdministratorInterface::class)->findOneBy(['username' => $adminUsername,]);

            if (empty($site) || empty($admin)) {
                $output->writeln('<error>' . 'Admin or Site was not found. Aborting.' . '</error>');

                return self::FAILURE;
            }

            if (!$admin->getAdministratorSites()->contains($site)) {
                $admin->getAdministratorSites()->add($site);
                $em->persist($admin);
                $em->flush();
            }

            $output->writeln('<info>' . 'Administrator is now allowed to administrate provided site' . '</info>');

        } catch (Exception $e) {
            $output->writeln('<error>' . $e->getMessage() . '</error>');

            return self::FAILURE;
        }

        return self::SUCCESS;
    }
}
