<?php

declare(strict_types=1);

namespace Autogedal\FeedMonitor\Model;

use Autogedal\FeedMonitor\Model\Adapter\SourceMonitorInterface;
use Psr\Log\LoggerInterface;

/**
 * Periodic checks no run reports by itself: runs that never finished, then the check of every source (jobs that
 * stopped running, the Magento cron), then reminders for alerts still open.
 */
class Checker
{
    /**
     * @param SourceMonitorInterface[] $sources from etc/di.xml
     */
    public function __construct(
        private readonly FeedMonitor $monitor,
        private readonly LoggerInterface $logger,
        private readonly array $sources = []
    ) {
    }

    /**
     * @param bool $outsideCron true from the server crontab (also checks the Magento cron), false from cron:run
     * @return string[] what was found, for the CLI
     */
    public function run(bool $outsideCron): array
    {
        $steps = ['stuck runs' => fn (): array => $this->monitor->closeStuckRuns()];
        foreach ($this->sources as $name => $source) {
            $steps[(string)$name] = fn (): array => $source->check($outsideCron);
        }

        $steps['reminders'] = function (): array {
            $this->monitor->remindOpenAlerts();
            return [];
        };

        $found = [];
        foreach ($steps as $name => $step) {
            try {
                $found = array_merge($found, $step());
            } catch (\Throwable $e) {
                $this->logger->error('Feed monitor check (' . $name . '): ' . $e->getMessage(), ['exception' => $e]);
                $found[] = 'Eroare la verificare (' . $name . '): ' . $e->getMessage();
            }
        }

        return $found;
    }
}
