<?php

declare(strict_types=1);

namespace App\Command;

use App\Entity\CustomerTracking;
use App\Entity\SitePerformance;
use App\Service\Mailer\Mailer;
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\Output\OutputInterface;
use Symfony\Component\Console\Style\SymfonyStyle;
use Symfony\Component\HttpKernel\KernelInterface;

#[AsCommand(name: 'app:clean', description: 'Nettoyage des données de performance (3j) et de tracking (30j)')]
class CleanCommand extends Command
{
    public function __construct(
        private readonly EntityManagerInterface $entityManager,
        ?string $name = null
    ) {
        parent::__construct($name);
    }

    protected function execute(InputInterface $input, OutputInterface $output): int
    {
        $io = new SymfonyStyle($input, $output);
        $io->title('Lancement du nettoyage de la base de données');

        // 1. Nettoyage SitePerformance (<= 3 jours)
        $limitPerformance = new \DateTime('-3 days');
        $perfCount = $this->entityManager->createQueryBuilder()
            ->delete(SitePerformance::class, 'p')
            ->where('p.createdAt <= :limit')
            ->setParameter('limit', $limitPerformance)
            ->getQuery()
            ->execute();

        $io->note(sprintf('%d entrées de performance supprimées (plus de 3 jours).', $perfCount));

        // 2. Nettoyage CustomerTracking (<= 30 jours)
        $limitTracking = new \DateTime('-30 days');
        $trackCount = $this->entityManager->createQueryBuilder()
            ->delete(CustomerTracking::class, 't')
            ->where('t.createAT <= :limit')
            ->setParameter('limit', $limitTracking)
            ->getQuery()
            ->execute();

        $io->note(sprintf('%d entrées de tracking supprimées (plus de 30 jours).', $trackCount));

        // Sauvegarde des changements
        $this->entityManager->flush();

        $io->success('Nettoyage terminé avec succès.');

        return Command::SUCCESS;
    }
}
