<?php

declare(strict_types=1);

namespace Autogedal\AwbRetry\Console\Command;

use Autogedal\AwbRetry\Model\Reconciliation;
use Magento\Framework\Console\Cli;
use Symfony\Component\Console\Command\Command;
use Symfony\Component\Console\Formatter\OutputFormatter;
use Symfony\Component\Console\Input\InputInterface;
use Symfony\Component\Console\Input\InputOption;
use Symfony\Component\Console\Output\OutputInterface;

class ReconcileCommand extends Command
{
    public function __construct(
        private readonly Reconciliation $reconciliation
    ) {
        parent::__construct();
    }

    protected function configure(): void
    {
        $this->setName('autogedal:awb-retry:reconcile')
            ->setDescription('Resolve stale retry logs from AWB numbers already saved locally')
            ->addOption('apply', null, InputOption::VALUE_NONE, 'Save changes; without this option only preview');
    }

    protected function execute(InputInterface $input, OutputInterface $output): int
    {
        $apply = (bool) $input->getOption('apply');
        $count = 0;
        try {
            foreach ($this->reconciliation->getCandidates() as $row) {
                if ($apply && !$this->reconciliation->resolve($row)) {
                    continue;
                }
                $output->writeln(sprintf('%s log #%d (AWB record #%d).',
                    $apply ? 'Resolved' : 'Would resolve', (int) $row['entity_id'], (int) $row['awb_id']));
                ++$count;
            }
        } catch (\Throwable $throwable) {
            $output->writeln('<error>' . OutputFormatter::escape($throwable->getMessage()) . '</error>');
            return Cli::RETURN_FAILURE;
        }

        $output->writeln(sprintf('%d %s.', $count, $apply ? 'logs resolved' : 'eligible logs; rerun with --apply to save'));
        return Cli::RETURN_SUCCESS;
    }
}
