<?php

namespace App\Jobs;

use App\Models\Project;
use App\Services\ExcelReportGenerator;
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 GenerateReport implements ShouldQueue
{
    use Dispatchable, InteractsWithQueue, Queueable, SerializesModels;

    public $timeout = 300;
    public $tries = 3;

    protected Project $project;

    public function __construct(Project $project)
    {
        $this->project = $project;
    }

    public function handle(ExcelReportGenerator $reportGenerator): void
    {
        Log::info('Generating report', ['project_id' => $this->project->id]);

        try {
            $fileName = $reportGenerator->generate($this->project);

            $this->project->update([
                'status' => 'completed',
                'excel_report_path' => $fileName,
                'completed_at' => now(),
            ]);

            Log::info('Report generated successfully', [
                'project_id' => $this->project->id,
                'file_name' => $fileName,
            ]);

        } catch (\Exception $e) {
            Log::error('Report generation failed', [
                'project_id' => $this->project->id,
                'error' => $e->getMessage(),
            ]);

            $this->project->update([
                'status' => 'failed',
                'error_message' => 'Report generation failed: ' . $e->getMessage(),
            ]);
        }
    }

    public function failed(\Throwable $exception): void
    {
        Log::error('GenerateReport job failed permanently', [
            'project_id' => $this->project->id,
            'error' => $exception->getMessage(),
        ]);

        $this->project->update([
            'status' => 'failed',
            'error_message' => 'Report generation failed after ' . $this->tries . ' attempts: ' . $exception->getMessage(),
        ]);
    }
}
