<?php

namespace App\Command;

use Doctrine\ORM\EntityManagerInterface;
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: 'app:email-tracking:purge',
    description: 'Supprime les EmailTracking et AppLog de plus de 90 jours',
)]
class PurgeEmailTrackingCommand extends Command
{
    public function __construct(
        private EntityManagerInterface $em,
    ) {
        parent::__construct();
    }

    protected function configure(): void
    {
        $this->addOption('days', null, InputOption::VALUE_REQUIRED, 'Nombre de jours de retention', '90');
    }

    protected function execute(InputInterface $input, OutputInterface $output): int
    {
        $io = new SymfonyStyle($input, $output);
        $days = (int) $input->getOption('days');
        $threshold = new \DateTimeImmutable("-{$days} days");

        $io->title("Purge EmailTracking (> $days jours)");
        $io->text('Seuil : '.$threshold->format('d/m/Y H:i:s'));

        $qb = $this->em->createQueryBuilder()
            ->delete('App\Entity\EmailTracking', 'e')
            ->where('e.sentAt < :threshold')
            ->setParameter('threshold', $threshold);

        $deleted = $qb->getQuery()->execute();

        $io->text("EmailTracking : $deleted enregistrement(s) supprime(s).");

        $deletedLogs = $this->em->createQueryBuilder()
            ->delete('App\Entity\AppLog', 'l')
            ->where('l.createdAt < :threshold')
            ->setParameter('threshold', $threshold)
            ->getQuery()
            ->execute();

        $io->text("AppLog : $deletedLogs enregistrement(s) supprime(s).");

        $io->success(($deleted + $deletedLogs).' enregistrement(s) supprime(s) au total.');

        return Command::SUCCESS;
    }
}
