<?php

namespace App\Jobs;

use App\Services\KJCHistoricalDataService;
use Illuminate\Bus\Queueable;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Foundation\Bus\Dispatchable;
use Illuminate\Queue\InteractsWithQueue;
use Illuminate\Queue\SerializesModels;
use Illuminate\Support\Facades\Log;

class CaptureKJCHistoricalDataJob implements ShouldQueue
{
    use Dispatchable, InteractsWithQueue, Queueable, SerializesModels;

    public $timeout = 300; // 5 minutes timeout

    public $tries = 3; // Retry 3 times if failed

    public $backoff = 60; // Wait 60 seconds between retries

    protected $month;

    protected $year;

    /**
     * Create a new job instance.
     */
    public function __construct($month = null, $year = null)
    {
        $this->month = $month;
        $this->year = $year;

        // Set queue name for Horizon monitoring
        $this->onQueue('kjc-historical-data');
    }

    /**
     * Execute the job.
     */
    public function handle(KJCHistoricalDataService $kjcHistoricalService)
    {
        try {
            Log::info('Starting KJC historical data capture job', [
                'month' => $this->month,
                'year' => $this->year,
                'job_id' => $this->job ? $this->job->getJobId() : 'manual-execution',
            ]);

            $success = $kjcHistoricalService->captureMonthlySnapshots($this->month, $this->year);

            if ($success) {
                Log::info('KJC historical data capture job completed successfully', [
                    'month' => $this->month,
                    'year' => $this->year,
                    'job_id' => $this->job ? $this->job->getJobId() : 'manual-execution',
                ]);
            } else {
                Log::error('KJC historical data capture job failed', [
                    'month' => $this->month,
                    'year' => $this->year,
                    'job_id' => $this->job ? $this->job->getJobId() : 'manual-execution',
                ]);

                throw new \Exception('KJC historical data capture failed');
            }

        } catch (\Exception $e) {
            Log::error('KJC historical data capture job exception', [
                'month' => $this->month,
                'year' => $this->year,
                'job_id' => $this->job ? $this->job->getJobId() : 'manual-execution',
                'error' => $e->getMessage(),
                'trace' => $e->getTraceAsString(),
            ]);

            throw $e;
        }
    }

    /**
     * Handle a job failure.
     */
    public function failed(\Throwable $exception)
    {
        Log::error('KJC historical data capture job failed permanently', [
            'month' => $this->month,
            'year' => $this->year,
            'job_id' => $this->job ? $this->job->getJobId() : 'manual-execution',
            'error' => $exception->getMessage(),
        ]);
    }

    /**
     * Get the tags that should be assigned to the job.
     */
    public function tags()
    {
        return ['kjc-historical-data', "month-{$this->month}", "year-{$this->year}"];
    }
}
