<?php

namespace App\Console\Commands;

use App\Http\Controllers\CronController;
use Illuminate\Console\Command;
use Illuminate\Support\Facades\Log;
use Throwable;

class RunRecurringCron extends Command
{
    /**
     * The name and signature of the console command.
     *
     * @var string
     */
    protected $signature = 'cron:run-recurring {--prepaid : Run prepaid recurring cron instead of regular recurring cron}';

    /**
     * The console command description.
     *
     * @var string
     */
    protected $description = 'Run recurring invoice cron logic from CLI';

    /**
     * Execute the console command.
     *
     * @return int
     */
    public function handle()
    {
        $isPrepaid = (bool) $this->option('prepaid');
        $task = $isPrepaid ? 'prepaid' : 'regular';

        $this->info("Starting recurring cron: {$task}");
        Log::info("CLI recurring cron started: {$task}");

        try {
            $controller = app(CronController::class);

            if ($isPrepaid) {
                $controller->recurring_prepaid_invoice_create_cron();
            } else {
                $controller->recurring_invoice_create_cron();
            }

            $this->info("Completed recurring cron: {$task}");
            Log::info("CLI recurring cron completed: {$task}");
            return self::SUCCESS;
        } catch (Throwable $e) {
            $this->error('Recurring cron failed: '.$e->getMessage());
            Log::error("CLI recurring cron failed ({$task}): ".$e->getMessage());
            return self::FAILURE;
        }
    }
}
