<?php

declare(strict_types=1);

namespace Autogedal\FeedMonitor\Console\Command;

use Autogedal\FeedMonitor\Model\AlertManager;
use Autogedal\FeedMonitor\Model\AlertNotifier;
use Autogedal\FeedMonitor\Model\Clock;
use Autogedal\FeedMonitor\Model\Config;
use Autogedal\FeedMonitor\Model\Problem;
use Magento\Framework\App\Area;
use Magento\Framework\App\State;
use Magento\Framework\Console\Cli;
use Symfony\Component\Console\Command\Command;
use Symfony\Component\Console\Input\InputInterface;
use Symfony\Component\Console\Output\OutputInterface;

class TestEmailCommand extends Command
{
    public function __construct(
        private readonly AlertNotifier $notifier,
        private readonly Config $config,
        private readonly Clock $clock,
        private readonly State $state
    ) {
        parent::__construct();
    }

    protected function configure(): void
    {
        $this->setName('autogedal:feed-monitor:test-email')
            ->setDescription('Feed monitor: send a test alert to the configured recipients');
    }

    protected function execute(InputInterface $input, OutputInterface $output): int
    {
        try {
            $this->state->setAreaCode(Area::AREA_CRONTAB);
        } catch (\Throwable) {
            // already set
        }
        if (!$this->config->isEmailEnabled()) {
            $output->writeln('<error>Alertele email sunt oprite (Feed Monitor > Alerte email > Trimite alerte).</error>');
            return Cli::RETURN_FAILURE;
        }

        $sent = $this->notifier->send(
            AlertManager::TYPE_ALERT,
            'test_email',
            Problem::FETCH,
            'Email de test trimis din bin/magento autogedal:feed-monitor:test-email. Nu este o problema reala.',
            $this->clock->format()
        );
        $output->writeln($sent
            ? 'Email trimis catre: ' . (implode(', ', $this->config->getRecipients()) ?: 'adresa expeditorului')
            : '<error>Emailul nu a plecat, vezi var/log/system.log / exception.log.</error>');

        return $sent ? Cli::RETURN_SUCCESS : Cli::RETURN_FAILURE;
    }
}
