<?php

namespace App\Console\Commands;

use App\Jobs\CaptureKJCHistoricalDataJob;
use App\Services\KJCHistoricalDataService;
use Carbon\Carbon;
use Illuminate\Console\Command;

class TriggerKJCHistoricalDataCapture extends Command
{
    /**
     * The name and signature of the console command.
     *
     * @var string
     */
    protected $signature = 'kjc:historical:trigger 
                            {--month= : Month to capture (1-12)}
                            {--year= : Year to capture (YYYY)}
                            {--queue : Dispatch to queue instead of running immediately}';

    /**
     * The console command description.
     *
     * @var string
     */
    protected $description = 'Manually trigger KJC historical data capture';

    /**
     * Execute the console command.
     */
    public function handle()
    {
        $month = $this->option('month');
        $year = $this->option('year');
        $useQueue = $this->option('queue');

        // If no month/year provided, use previous month
        if (! $month || ! $year) {
            $lastMonth = Carbon::now()->subMonth();
            $month = $month ?: $lastMonth->format('m');
            $year = $year ?: $lastMonth->format('Y');
        }

        $this->info("Triggering KJC historical data capture for {$month}/{$year}...");

        try {
            if ($useQueue) {
                // Dispatch to queue
                CaptureKJCHistoricalDataJob::dispatch($month, $year);
                $this->info('✓ KJC historical data capture job dispatched to queue');
                $this->info('You can monitor the job in Horizon dashboard');
            } else {
                // Run immediately
                $job = new CaptureKJCHistoricalDataJob($month, $year);
                $job->handle(app(KJCHistoricalDataService::class));
                $this->info('✓ KJC historical data capture completed immediately');
            }

        } catch (\Exception $e) {
            $this->error('Error: '.$e->getMessage());

            return 1;
        }

        return 0;
    }
}
