<?php

declare(strict_types=1);

namespace Kylin\Education\Http\Controllers;

use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;
use Illuminate\Routing\Controller;
use Kylin\Education\Models\Question;

/**
 * 试题控制器
 */
class QuestionController extends Controller
{
    public function index(Request $request): JsonResponse
    {
        $query = Question::with('course');

        if ($request->filled('type')) {
            $query->where('type', $request->input('type'));
        }
        if ($request->filled('difficulty')) {
            $query->where('difficulty', $request->input('difficulty'));
        }
        if ($request->filled('course_id')) {
            $query->where('course_id', $request->input('course_id'));
        }

        $questions = $query->paginate($request->input('per_page', 15));

        return response()->json(['code' => 0, 'data' => $questions]);
    }

    public function store(Request $request): JsonResponse
    {
        $validated = $request->validate([
            'course_id' => 'nullable|exists:courses,id',
            'type' => 'required|in:single_choice,multi_choice,judgment,fill_blank,short_answer',
            'content' => 'required|string',
            'options' => 'nullable|array',
            'answer' => 'required|string',
            'analysis' => 'nullable|string',
            'difficulty' => 'nullable|in:easy,medium,hard',
            'score' => 'nullable|integer|min:1',
            'knowledge_tags' => 'nullable|array',
        ]);

        $question = Question::create($validated);

        return response()->json(['code' => 0, 'data' => $question], 201);
    }

    public function show(Question $question): JsonResponse
    {
        return response()->json(['code' => 0, 'data' => $question]);
    }

    public function update(Request $request, Question $question): JsonResponse
    {
        $validated = $request->validate([
            'course_id' => 'nullable|exists:courses,id',
            'type' => 'sometimes|in:single_choice,multi_choice,judgment,fill_blank,short_answer',
            'content' => 'sometimes|string',
            'options' => 'nullable|array',
            'answer' => 'sometimes|string',
            'analysis' => 'nullable|string',
            'difficulty' => 'nullable|in:easy,medium,hard',
            'score' => 'nullable|integer|min:1',
            'knowledge_tags' => 'nullable|array',
        ]);

        $question->update($validated);

        return response()->json(['code' => 0, 'data' => $question]);
    }

    public function destroy(Question $question): JsonResponse
    {
        $question->delete();

        return response()->json(['code' => 0, 'message' => '删除成功']);
    }

    public function import(Request $request): JsonResponse
    {
        $request->validate([
            'file' => 'required|file|mimes:xlsx,xls',
        ]);

        return response()->json(['code' => 0, 'message' => '导入任务已创建']);
    }
}
