<?php

namespace App\Http\Controllers\Admin\Quiz;

use App\Enums\QuestionTypeEnum;
use App\Exceptions\CustomWebException;
use App\Models\Language;
use App\Models\QuestionTranslation;
use App\Models\Quiz;
use App\Models\QuizQuestion;
use App\Services\Ai\Ai;
use Illuminate\Http\Request;

class AiQuestionController extends QuestionController
{
    public function createWithAi(Quiz $quiz)
    {
        adminUserHasPermission(permission: 'create');

        $questionLevel = $this->getQuestionLevel($quiz);

        $buttons = [
            [
                'label' => __('Back'),
                'icon' => 'ph ph-arrow-clockwise',
                'type' => 'link',
                'link' => route('admin.quizzes.questions.index', ['quiz' => $quiz->id, 'label' => $questionLevel ? $questionLevel->level->slug : null]),
            ],
        ];

        return view('admin.pages.quiz.questions.create-ai', compact('buttons', 'quiz', 'questionLevel'));
    }

    public function editWithAi(Quiz $quiz)
    {
        adminUserHasPermission(permission: 'edit');

        $questionLevel = $this->getQuestionLevel($quiz);

        $buttons = [
            [
                'label' => __('Back'),
                'icon' => 'ph ph-back',
                'type' => 'link',
                'link' => route('admin.quizzes.questions.index', ['quiz' => $quiz->id]),
            ],
        ];

        $translations = QuestionTranslation::whereHasMorph('questionable', [QuizQuestion::class], function ($query) use ($quiz, $questionLevel) {
            $query->where('quiz_id', $quiz->id);

            if ($questionLevel) {
                $query->where('question_level_id', $questionLevel->id);
            } else {
                $query->whereNull('question_level_id');
            }
        })
            ->get();

        return view('admin.pages.quiz.questions.edit-ai', compact('buttons', 'quiz', 'translations', 'questionLevel'));
    }

    public function generateQuestionByAi(Request $request, Quiz $quiz)
    {
        adminUserHasPermission(permission: 'edit');
        $locale = $request->locale ?? 'en';

        if ($locale == 'en') {
            $request->validate([
                'question_type' => 'required|in:'.implode(',', QuestionTypeEnum::values()),
                'question_count' => 'required|integer|min:1',
                'score' => 'required|numeric|min:0',
                'time_limit' => 'required|numeric|min:0',
                'topic_details' => 'required|string|max:500',
            ]);
        }

        $language = Language::where('code', $request->locale)->first();

        if (! $language) {
            throw new CustomWebException(__('Language not found'));
        }

        $ai = app(Ai::class);
        // when locale is en then create question with full details
        if ($locale == 'en') {
            $questions = $ai->buildQuestionPrompt(type: QuestionTypeEnum::from($request->question_type), topic: $quiz->category->title, topic_details: $request->topic_details, level: $quiz->quiz_level, questionCount: $request->question_count, language: $language->name)
                ->process();
            /**
             * creating questions with full details using ai
             */
            $ai->storeQuestion(questions: $questions, contest: $quiz, language: $language, request: $request);

            return response()->json([
                'message' => __('Questions were successfully generated'),
                'redirect' => route('admin.quizzes.questions.index', ['quiz' => $quiz->id]),
            ]);
        } else {
            /**
             * update question languages using ai
             */
            $ai->updateQuestionLanguages(contest: $quiz, language: $language, request: $request);

            return response()->json([
                'message' => __('Translation was successfully generated'),
                'reload' => true,
            ]);
        }
    }
}
