<?php

namespace Console\Commands;

use Carbon\Carbon;
use Openguru\OpenCartFramework\Config\Settings;
use Openguru\OpenCartFramework\Scheduler\SchedulerService;
use Symfony\Component\Console\Command\Command;
use Symfony\Component\Console\Input\InputInterface;
use Symfony\Component\Console\Output\OutputInterface;

class ScheduleRunCommand extends TeleCartCommand
{
    private SchedulerService $scheduler;
    private Settings $settings;

    protected static $defaultName = 'schedule:run';
    protected static $defaultDescription = 'Run scheduled commands';

    public function __construct(SchedulerService $scheduler, Settings $settings)
    {
        parent::__construct();
        $this->scheduler = $scheduler;
        $this->settings = $settings;
    }

    protected function execute(InputInterface $input, OutputInterface $output): int
    {
        $mode = $this->settings->get('cron.mode', 'disabled');
        if ($mode !== 'system') {
            $output->writeln('<comment>Scheduler is disabled. Skipping CLI execution.</comment>');

            return Command::SUCCESS;
        }

        $output->writeln(sprintf(
            '[%s] <info>TeleCart Scheduler Running...</info>',
            Carbon::now()->toJSON(),
        ));

        $result = $this->scheduler->run();

        // Print Executed
        if (empty($result->executed)) {
            $output->writeln('No tasks executed.');
        } else {
            foreach ($result->executed as $item) {
                $output->writeln(sprintf('<info>Executed:</info> %s (%.4fs)', $item['name'], $item['duration']));
            }
        }

        // Print Failed
        foreach ($result->failed as $item) {
            $output->writeln(sprintf('<error>Failed:</error> %s - %s', $item['name'], $item['error']));
        }

        // Print Skipped (verbose only)
        if ($output->isVerbose()) {
            foreach ($result->skipped as $item) {
                $output->writeln(sprintf('<comment>Skipped:</comment> %s - %s', $item['name'], $item['reason']));
            }
        }

        return Command::SUCCESS;
    }
}
