<?php

declare(strict_types=1);

/**
 * Reintento manual/programado de avisos de cobro SaaS.
 *
 * Uso:
 *   /Applications/XAMPP/xamppfiles/bin/php scripts/subscription_notice_retry.php [limit]
 */

define('BASE_PATH', dirname(__DIR__));

require BASE_PATH . '/app/helpers/env.php';
load_env(BASE_PATH . '/.env');
require BASE_PATH . '/app/helpers/functions.php';

spl_autoload_register(static function (string $class): void {
    $prefix = 'App\\';
    if (!str_starts_with($class, $prefix)) {
        return;
    }

    $relative = substr($class, strlen($prefix));
    $parts = explode('\\', $relative);
    $file = array_pop($parts);
    $directory = implode('/', array_map('strtolower', $parts));
    $path = BASE_PATH . '/app/' . ($directory !== '' ? $directory . '/' : '') . $file . '.php';

    if (is_file($path)) {
        require $path;
    }
});

date_default_timezone_set((string) config('app.timezone', 'America/Bogota'));

$limit = isset($argv[1]) ? max(1, min(1000, (int) $argv[1])) : 200;

try {
    $result = (new App\Services\SubscriptionAutomationService())->retryPendingNotices($limit);
    echo json_encode($result, JSON_UNESCAPED_UNICODE | JSON_PRETTY_PRINT) . PHP_EOL;

    $hasErrors = is_array($result['errors'] ?? null) && $result['errors'] !== [];
    exit($hasErrors ? 1 : 0);
} catch (Throwable $e) {
    fwrite(STDERR, '[FAIL] Reintento de avisos: ' . $e->getMessage() . PHP_EOL);
    exit(1);
}
