<?php

namespace App\Jobs;

use App\Models\PlotSurvey;
use App\Services\PlotSurveyAnalyzerService;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Foundation\Queue\Queueable;
use Illuminate\Queue\InteractsWithQueue;
use Illuminate\Queue\SerializesModels;

class AnalyzePlotSurvey implements ShouldQueue
{
    use Queueable, InteractsWithQueue, SerializesModels;

    public int $timeout = 120;    // 2 minutes max
    public int $tries   = 2;

    public function __construct(public readonly PlotSurvey $survey) {}

    public function handle(PlotSurveyAnalyzerService $analyzer): void
    {
        $analyzer->analyze($this->survey);
    }

    public function failed(\Throwable $e): void
    {
        $this->survey->update([
            'ai_status' => 'failed',
            'ai_error'  => $e->getMessage(),
        ]);
    }
}
