<?php

namespace AutoAdmin\Bundle\Content\Command;

use AutoAdmin\Bundle\Content\Entity\Log;
use AutoAdmin\Bundle\Content\Repository\LogRepository;
use Symfony\Bridge\Doctrine\ManagerRegistry;
use Symfony\Component\Console\Command\Command;
use Symfony\Component\Console\Input\InputInterface;
use Symfony\Component\Console\Input\InputOption;
use Symfony\Component\Console\Output\OutputInterface;
use Symfony\Component\Console\Style\SymfonyStyle;

class ClearLogCommand extends Command
{
    protected static $defaultName = 'aa:content:clear-log';
    private ManagerRegistry $managerRegistry;
    private SymfonyStyle $io;
    private LogRepository $logRepository;

    public function __construct(
        ManagerRegistry $managerRegistry,
        string          $name = null
    )
    {
        parent::__construct($name);
        $this->managerRegistry = $managerRegistry;
        $this->logRepository = $this->managerRegistry->getRepository(Log::class);
    }

    protected function configure()
    {
        $this
            ->setDescription('Clear log of entities')
            ->addOption('limit', null, InputOption::VALUE_OPTIONAL, 'Limit of logs to delete', 100000)
            ->addOption('before', null, InputOption::VALUE_OPTIONAL, 'Delete logs before this date (PHP datetime formats)', '-2 months')
            ->addOption('alert', null, InputOption::VALUE_OPTIONAL, 'Alert if more than this number of logs', 1000);
    }

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

        $this->clearLogs(new \DateTime($input->getOption('before')), $input->getOption('limit'));

        $this->checkAlert($input->getOption('alert'));

        return Command::SUCCESS;
    }

    private function clearLogs(\DateTime $before, int $limit)
    {
        $logs = $this->logRepository->findBefore($before, $limit);
        $logsCount = count($logs);

        $this->io->info('Found ' . $logsCount . ' logs to delete');

        $progressBar = $this->io->createProgressBar($logsCount);
        $progressBar->start();
        $em = $this->managerRegistry->getManager();
        foreach ($logs as $log) {
            $em->remove($log);
            $progressBar->advance();
        }
        $em->flush();
        $progressBar->finish();
        $this->io->newLine(2);

        $this->io->success('Deleted ' . $logsCount . ' logs');
    }

    private function checkAlert(int $alert)
    {
        $logsCount = $this->logRepository->count([]);
        if ($logsCount > $alert) {
            $this->io->warning('There are ' . $logsCount . ' logs in database');
            $this->alert();
        }
    }

    private function alert()
    {
        // TODO: alert canal, mail, Slack, etc.
    }
}
