<?php

declare(strict_types=1);

namespace Autogedal\FeedMonitor\Console\Command;

use Autogedal\FeedMonitor\Model\JobRegistry;
use Autogedal\FeedMonitor\Model\MonitorKey;
use Autogedal\FeedMonitor\Model\StateRepository;
use Magento\Framework\Console\Cli;
use Symfony\Component\Console\Command\Command;
use Symfony\Component\Console\Input\InputArgument;
use Symfony\Component\Console\Input\InputInterface;
use Symfony\Component\Console\Input\InputOption;
use Symfony\Component\Console\Output\OutputInterface;

/**
 * Lets the next run of a job / sub-feed update stock or prices although its feed is much smaller than usual
 * (the supplier really removed products).
 */
class AllowIncompleteCommand extends Command
{
    public function __construct(
        private readonly JobRegistry $jobs,
        private readonly StateRepository $states
    ) {
        parent::__construct();
    }

    protected function configure(): void
    {
        $this->setName('autogedal:feed-monitor:allow-incomplete')
            ->setDescription('Feed monitor: the next run of a job may update from a feed smaller than the threshold')
            ->addArgument('job', InputArgument::REQUIRED, 'Job code, e.g. alfaromtrans_paravanturi_stock')
            ->addOption('feed', null, InputOption::VALUE_REQUIRED, 'Sub-feed code, for jobs with sub-feeds');
    }

    protected function execute(InputInterface $input, OutputInterface $output): int
    {
        $jobCode = (string)$input->getArgument('job');
        $feedCode = (string)$input->getOption('feed');
        if (!$this->jobs->has($jobCode)) {
            $output->writeln('<error>Job necunoscut. Joburi urmarite: ' . implode(', ', $this->jobs->getJobCodes()) . '</error>');
            return Cli::RETURN_FAILURE;
        }
        $feeds = $this->jobs->getFeedCodes($jobCode);
        if ($feeds && !in_array($feedCode, $feeds, true)) {
            $output->writeln('<error>Jobul are sub-feed-uri, alege unul cu --feed: ' . implode(', ', $feeds) . '</error>');
            return Cli::RETURN_FAILURE;
        }
        if (!$feeds && $feedCode !== '') {
            $output->writeln('<error>Jobul nu are sub-feed-uri, ruleaza fara --feed.</error>');
            return Cli::RETURN_FAILURE;
        }

        $this->states->allowIncomplete(MonitorKey::build($jobCode, $feedCode));
        $output->writeln(sprintf(
            'Urmatoarea rulare a %s va actualiza chiar daca feed-ul este sub prag (o singura data, valabil %d ore).',
            $this->jobs->getLabel($jobCode, $feedCode),
            StateRepository::ALLOWANCE_HOURS
        ));

        return Cli::RETURN_SUCCESS;
    }
}
