<?php

namespace App\Console\Commands;

use App\Jobs\CapturePKJHistoricalDataJob;
use App\Services\PKJHistoricalDataService;
use Carbon\Carbon;
use Illuminate\Console\Command;

class TriggerPKJHistoricalDataCapture extends Command
{
    protected $signature = 'pkj:historical:trigger 
                            {--month= : Month to capture (1-12)}
                            {--year= : Year to capture (YYYY)}
                            {--queue : Dispatch to queue instead of running immediately}';

    protected $description = 'Manually trigger PKJ historical data capture';

    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 PKJ historical data capture for {$month}/{$year}...");

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

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

            return 1;
        }

        return 0;
    }
}
