<?php

namespace App\Jobs;

use App\Models\Question;
use App\Services\AiSolutionService;
use Illuminate\Bus\Queueable;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Foundation\Bus\Dispatchable;
use Illuminate\Queue\InteractsWithQueue;
use Illuminate\Queue\SerializesModels;

class GenerateSolutionJob implements ShouldQueue
{
    use Dispatchable;
    use InteractsWithQueue;
    use Queueable;
    use SerializesModels;

    public function __construct(public readonly int $questionId)
    {
    }

    public function handle(AiSolutionService $service): void
    {
        $question = Question::find($this->questionId);
        if (!$question) {
            return;
        }

        $result = $service->generateSolution($question->stem ?? '', [
            'question_type' => $question->question_type,
            'kp_code' => $question->kp_code,
        ]);

        $question->solution = $result['solution'] ?? $question->solution;
        if (!empty($result['steps'])) {
            $meta = $question->meta ?? [];
            $meta['solution_steps'] = $result['steps'];
            $question->meta = $meta;
        }
        $question->save();
    }
}
