<?php

namespace App\Commands;

use App\Libraries\YemscanService;
use App\Models\YemTransactionModel;
use CodeIgniter\CLI\BaseCommand;
use CodeIgniter\CLI\CLI;

/**
 * Refresh YEM recorded transaction statuses from the YEMScan API.
 * Run via cron (e.g. every 5 min): php spark yem:refresh-statuses
 */
class YemRefreshStatuses extends BaseCommand
{
    protected $group       = 'YEM';
    protected $name        = 'yem:refresh-statuses';
    protected $description = 'Refresh statuses of recorded YEM transactions from the YEMScan API (for cron or manual run).';
    protected $usage       = 'yem:refresh-statuses [limit]';

    public function run(array $params)
    {
        $limit = isset($params[0]) && is_numeric($params[0]) ? (int) $params[0] : 100;

        $yemscanService = new YemscanService();
        if (! $yemscanService->isConfigured()) {
            CLI::error('YEMScan is not configured (check .env: yemscan.api_key, yemscan.custom_domain, yemscan.pernum).');
            return EXIT_ERROR;
        }

        $model = new YemTransactionModel();
        try {
            $updated = $model->refreshStatuses($yemscanService, $limit);
        } catch (\Throwable $e) {
            CLI::error('Refresh failed: ' . $e->getMessage());
            return EXIT_ERROR;
        }

        CLI::write('YEM statuses refreshed: ' . $updated . ' transaction(s) updated.', 'green');
        return EXIT_SUCCESS;
    }
}
