<?php
declare(strict_types=1);

namespace CronJobs;

use App\Core\App;
use App\Core\Database;
use App\Core\Logger;
use App\Modules\Waiver\Services\WaiverProcessor;

class WaiverAutoCompleteJob
{
    private Database $db;
    public function __construct(Database $db) { $this->db = $db; }

    public function shouldRun(): bool
    {
        return true;
    }

    public function run(): array
    {
        $pending = $this->db->select(
            "SELECT id FROM waiver_requests WHERE status = 'fee_paid' ORDER BY updated_at ASC LIMIT 10"
        );

        if (empty($pending)) {
            return ['processed' => 0, 'pending' => 0];
        }

        $processed = 0;
        $deferred = 0;

        foreach ($pending as $row) {
            try {
                $result = WaiverProcessor::autoComplete((int) $row['id']);
                if ($result['success'] ?? false) {
                    $processed++;
                    Logger::info("WaiverAutoCompleteJob: completed waiver #{$row['id']}");
                } else {
                    $deferred++;
                    Logger::info("WaiverAutoCompleteJob: deferred waiver #{$row['id']}: " . ($result['reason'] ?? 'unknown'));
                }
            } catch (\Throwable $e) {
                Logger::error("WaiverAutoCompleteJob: failed waiver #{$row['id']}: " . $e->getMessage());
            }
        }

        return ['processed' => $processed, 'deferred' => $deferred, 'total_pending' => count($pending)];
    }
}
