<?php

namespace AutoAdmin\Bundle\Cache\Command;

use AutoAdmin\Bundle\Admin\Helper\EntityHelper;
use AutoAdmin\Bundle\Cache\Entity\CacheLog;
use DateTime;
use Symfony\Component\Console\Attribute\AsCommand;
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;

#[AsCommand(name: 'aa:cache:clear-log')]
class ClearCacheLogCommand extends Command
{
    private EntityHelper $entityHelper;

    public function __construct(
        EntityHelper $entityHelper,
        string $name = null
    )
    {
        parent::__construct($name);
        $this->entityHelper = $entityHelper;
    }

    protected function configure(): void
    {
        $this
            ->setDescription('Clear log of clear cache')
            ->addOption('limit', null, InputOption::VALUE_OPTIONAL, 'Limit of cache logs to delete', 100000)
        ;
    }

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

        $cacheLogRepository = $this->entityHelper->getManager()->getRepository(CacheLog::class);
        $cacheLogs = $cacheLogRepository->findBefore(new DateTime('-10 days'), $input->getOption('limit'));
        $cacheLogsCount = count($cacheLogs);

        $io->info('Found '.$cacheLogsCount.' cache logs to delete');

        $progressBar = $io->createProgressBar($cacheLogsCount);
        $progressBar->start();
        $em = $this->entityHelper->getManager();
        foreach ($cacheLogs as $cacheLog) {
            $em->remove($cacheLog);
            $progressBar->advance();
        }
        $em->flush();
        $progressBar->finish();
        $io->newLine(2);

        $io->success('Deleted '.$cacheLogsCount.' cache logs');

        return Command::SUCCESS;
    }
}
