<?php

namespace Console\Commands;

use Openguru\OpenCartFramework\Container\Container;
use Openguru\OpenCartFramework\Scheduler\ScheduleJobRegistry;
use Openguru\OpenCartFramework\Scheduler\SchedulerService;
use Symfony\Component\Console\Command\Command;
use Symfony\Component\Console\Helper\Table;
use Symfony\Component\Console\Input\InputInterface;
use Symfony\Component\Console\Output\OutputInterface;

class ScheduleListCommand extends TeleCartCommand
{
    private SchedulerService $schedulerService;
    private Container $container;

    protected static $defaultName = 'schedule:list';
    protected static $defaultDescription = 'List all scheduled tasks and their status';

    public function __construct(SchedulerService $schedulerService, Container $container)
    {
        parent::__construct();
        $this->schedulerService = $schedulerService;
        $this->container = $container;
    }

    protected function execute(InputInterface $input, OutputInterface $output): int
    {
        $registry = new ScheduleJobRegistry($this->container);

        // Load schedule config
        $configFile = BP_PHAR_BASE_PATH . '/configs/schedule.php';
        if (file_exists($configFile)) {
            $scheduler = $registry; // Variable name used in config file
            require $configFile;
        }

        $jobs = $registry->getJobs();
        $table = new Table($output);
        $table->setHeaders(['Name / Class', 'Cron Expression', 'Last Run', 'Last Failure']);

        foreach ($jobs as $job) {
            $id = $job->getId();
            $lastRun = $this->schedulerService->getLastRun($id);
            $lastFailure = $this->schedulerService->getLastFailure($id);

            $lastRunText = $lastRun ? date('Y-m-d H:i:s', $lastRun) : 'Never';
            
            $lastFailureText = 'None';
            if ($lastFailure) {
                $lastFailureText = date('Y-m-d H:i:s', $lastFailure['time']) . "\n" . substr($lastFailure['message'], 0, 50);
            }

            $table->addRow([
                $job->getName(),
                // We don't have getExpression public yet on Job, assuming we might need to add it or it's not critical. 
                // Wait, Job class stores expression but doesn't expose it via public getter.
                // I should add getExpression() to Job.php if I want to show it.
                // For now, let's assume we add it.
                method_exists($job, 'getExpression') ? $job->getExpression() : '???',
                $lastRunText,
                $lastFailureText
            ]);
        }

        $table->render();

        return Command::SUCCESS;
    }
}

