<?php

declare(strict_types=1);

namespace Autogedal\FeedMonitor\Plugin\Firebear;

use Autogedal\FeedMonitor\Model\Adapter\FirebearJobMonitor;
use Firebear\ImportExport\Api\Data\ImportInterface;
use Firebear\ImportExport\Model\Job\Handler\SummaryHandler;
use Psr\Log\LoggerInterface;

/**
 * Records the result of a Firebear import when it ends. SummaryHandler is the handler that dispatches
 * firebear_import_success / firebear_import_failure; it is called with the job, the file of the run that just ended
 * (its history row and log) and its status, so the result is read from that run and not from the job's latest one.
 *
 * Monitored: imports run by cron, CLI (import:job:run) and API, which go through Firebear's RunById and its handlers.
 * Not monitored, on purpose: imports started by hand from the admin (System > Import Jobs > Run), which use
 * Helper::runImport() and skip the handlers.
 *
 * Never stops the import: its own errors are only logged.
 */
class RecordImportResult
{
    public function __construct(
        private readonly FirebearJobMonitor $firebearMonitor,
        private readonly LoggerInterface $logger
    ) {
    }

    /**
     * @param mixed $result
     * @param string $file
     * @param int $status
     * @return mixed
     */
    public function afterExecute(SummaryHandler $subject, $result, ImportInterface $job, $file, $status)
    {
        $jobId = (int)$job->getId();
        try {
            if ($jobId > 0) {
                $this->firebearMonitor->recordImport($jobId, (string)$file, (bool)$status);
            }
        } catch (\Throwable $e) {
            $this->logger->error('Feed monitor: cannot record the Firebear import ' . $file . ' of job ' . $jobId . ': ' . $e->getMessage());
        }

        return $result;
    }
}
