<?php

namespace App\Http\Controllers\Admin\Contest;

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

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

        $buttons = [
            [
                'label' => __('Back'),
                'icon' => 'ph ph-arrow-clockwise',
                'type' => 'link',
                'link' => route('admin.contests.questions.index', ['contest' => $contest->id]),
            ],
        ];

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

    public function editWithAi(Contest $contest)
    {
        adminUserHasPermission(permission: 'edit');

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

        $translations = QuestionTranslation::whereHasMorph('questionable', [ContestQuestion::class], function ($query) use ($contest) {
            $query->where('contest_id', $contest->id);
        })
            ->get();

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

    public function generateQuestionByAi(Request $request, Contest $contest)
    {
        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: $contest->category->title, topic_details: $request->topic_details, level: $contest->contest_level, questionCount: $request->question_count, language: $language->name)
                ->process();

            /**
             * creating questions with full details using ai
             */
            $ai->storeQuestion(questions: $questions, contest: $contest, language: $language, request: $request);

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

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