<?php

namespace App\Command;

use App\Entity\MessengerLog;
use App\Service\MailerService;
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;

#[AsCommand(
    name: 'app:monitor:messenger',
    description: 'Check for failed Messenger messages and notify admin',
)]
class MonitorMessengerCommand extends Command
{
    public function __construct(
        private EntityManagerInterface $em,
        private MailerService $mailer,
    ) {
        parent::__construct();
    }

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

        $failedMessages = $this->em->getRepository(MessengerLog::class)->findBy(
            ['status' => 'failed'],
            ['createdAt' => 'DESC'],
            50,
        );

        $count = \count($failedMessages);

        if (0 === $count) {
            $io->success('No failed messages.');

            return Command::SUCCESS;
        }

        $io->warning($count.' failed message(s) found.');

        $html = '<h2>'.$count.' message(s) en echec</h2><table style="width:100%;border-collapse:collapse;">';
        $html .= '<tr style="background:#111827;color:#fff;"><th style="padding:8px;text-align:left;">Classe</th><th style="padding:8px;">Date</th><th style="padding:8px;">Erreur</th></tr>';

        foreach ($failedMessages as $log) {
            $html .= '<tr style="border-bottom:1px solid #eee;">';
            $html .= '<td style="padding:8px;font-weight:bold;">'.$log->getMessageClass().'</td>';
            $html .= '<td style="padding:8px;">'.$log->getCreatedAt()->format('d/m/Y H:i').'</td>';
            $html .= '<td style="padding:8px;font-size:12px;color:#666;">'.mb_substr($log->getErrorMessage() ?? '', 0, 200).'</td>';
            $html .= '</tr>';
        }
        $html .= '</table>';

        $this->mailer->sendEmail(
            $this->mailer->getAdminEmail(),
            '[E-Ticket] '.$count.' message(s) Messenger en echec',
            $html,
            null,
            null,
            false,
        );

        $io->info('Notification sent to '.$this->mailer->getAdminEmail());

        return Command::SUCCESS;
    }
}
