<?php

namespace App\Jobs;

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

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

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

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

        $matches = $service->matchKnowledgePoints($question->stem ?? '');
        $hasValidKp = $service->isValidKnowledgePoint($question->kp_code);

        if (empty($matches) || !$hasValidKp) {
            $matches = $service->matchKnowledgePointsByAi($question->stem ?? '');
        }

        if (!empty($matches)) {
            $question->kp_code = $matches[0]['kp_code'] ?? $question->kp_code;
            $question->save();
        }

        foreach ($matches as $match) {
            QuestionKpRelation::updateOrCreate([
                'question_id' => $question->id,
                'kp_code' => $match['kp_code'] ?? '',
            ], [
                'weight' => $match['weight'] ?? 1,
            ]);
        }
    }
}
