<?php

namespace App\Jobs;

use App\Services\PKJHistoricalDataService;
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 CapturePKJHistoricalDataJob 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('pkj-historical-data');
    }

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

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

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

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

        } catch (\Exception $e) {
            Log::error('PKJ 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('PKJ 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 ['pkj-historical-data', "month-{$this->month}", "year-{$this->year}"];
    }
}
