<?php

declare(strict_types=1);

namespace App\Module\Mail\Infrastructure\Console;

use App\Module\Mail\Domain\Repository\MailMessageRepositoryInterface;
use App\Module\Mail\Infrastructure\Imap\MimeHeaderDecoder;
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:mail:redecode-headers',
    description: 'Re-décode les sujets et noms d\'expéditeur encodés en MIME (RFC 2047) déjà stockés en base',
)]
final class MailRedecodeHeadersCommand extends Command
{
    public function __construct(
        private readonly MailMessageRepositoryInterface $messageRepository,
        private readonly EntityManagerInterface $entityManager,
    ) {
        parent::__construct();
    }

    protected function configure(): void
    {
        $this->addOption(
            'dry-run',
            null,
            InputOption::VALUE_NONE,
            'Affiche les changements sans écrire en base',
        );
    }

    protected function execute(InputInterface $input, OutputInterface $output): int
    {
        $io       = new SymfonyStyle($input, $output);
        $isDryRun = (bool) $input->getOption('dry-run');

        $messages = $this->messageRepository->findAll();
        $io->text(sprintf('%d message(s) à examiner...', count($messages)));

        $changed = 0;

        foreach ($messages as $message) {
            $newSubject  = MimeHeaderDecoder::decode($message->getSubject());
            $newFromName = MimeHeaderDecoder::decode($message->getFromName());

            $hasChange = $newSubject !== $message->getSubject() || $newFromName !== $message->getFromName();

            if (!$hasChange) {
                continue;
            }

            if ($io->isVerbose()) {
                $io->text(sprintf(' - #%d : "%s" → "%s"', $message->getId(), (string) $message->getSubject(), (string) $newSubject));
            }

            if (!$isDryRun) {
                $message->setSubject($newSubject);
                $message->setFromName($newFromName);
            }

            ++$changed;
        }

        if (!$isDryRun) {
            $this->entityManager->flush();
        }

        $io->success(sprintf(
            '%s%d en-tête(s) re-décodé(s).',
            $isDryRun ? '[dry-run] ' : '',
            $changed,
        ));

        return Command::SUCCESS;
    }
}
