<?php

declare(strict_types=1);

namespace Autogedal\FeedMonitor\Console\Command;

use Autogedal\FeedMonitor\Model\Checker;
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\Input\InputOption;
use Symfony\Component\Console\Output\OutputInterface;

/**
 * Run from the server crontab, apart from cron:run, so a stopped Magento cron is still reported:
 *   0,30 * * * * php /path/to/magento/bin/magento autogedal:feed-monitor:check
 */
class CheckCommand extends Command
{
    public function __construct(
        private readonly Checker $checker,
        private readonly State $state
    ) {
        parent::__construct();
    }

    protected function configure(): void
    {
        $this->setName('autogedal:feed-monitor:check')
            ->setDescription('Feed monitor: Magento cron down, jobs not running / not finished, reminders')
            ->addOption('no-cron', null, InputOption::VALUE_NONE, 'Do not check that the Magento cron runs');
    }

    protected function execute(InputInterface $input, OutputInterface $output): int
    {
        try {
            $this->state->setAreaCode(Area::AREA_CRONTAB);
        } catch (\Throwable) {
            // already set
        }

        $found = $this->checker->run(!$input->getOption('no-cron'));
        foreach ($found as $line) {
            $output->writeln($line);
        }
        $output->writeln($found ? count($found) . ' probleme gasite (alertele se trimit conform setarilor).' : 'Nicio problema.');

        return Cli::RETURN_SUCCESS;
    }
}
