<?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\Exam;

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

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

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

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

    public function store(Request $request): JsonResponse
    {
        $validated = $request->validate([
            'name' => 'required|string|max:200',
            'course_id' => 'nullable|exists:courses,id',
            'type' => 'required|in:fixed,random',
            'duration' => 'required|integer|min:1',
            'pass_score' => 'required|integer|min:0',
            'total_score' => 'required|integer|min:1',
            'start_time' => 'required|date',
            'end_time' => 'required|date|after:start_time',
            'anti_cheat' => 'nullable|array',
        ]);

        $exam = Exam::create($validated);

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

    public function show(Exam $exam): JsonResponse
    {
        $exam->load(['course', 'questions.question']);

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

    public function update(Request $request, Exam $exam): JsonResponse
    {
        $validated = $request->validate([
            'name' => 'sometimes|string|max:200',
            'course_id' => 'nullable|exists:courses,id',
            'type' => 'sometimes|in:fixed,random',
            'duration' => 'sometimes|integer|min:1',
            'pass_score' => 'sometimes|integer|min:0',
            'total_score' => 'sometimes|integer|min:1',
            'start_time' => 'sometimes|date',
            'end_time' => 'sometimes|date|after:start_time',
            'anti_cheat' => 'nullable|array',
        ]);

        $exam->update($validated);

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

    public function destroy(Exam $exam): JsonResponse
    {
        $exam->delete();

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

    public function start(Exam $exam): JsonResponse
    {
        // 创建答题记录
        $attempt = $exam->attempts()->create([
            'student_id' => auth()->user()->student->id ?? null,
            'started_at' => now(),
            'status' => 'in_progress',
        ]);

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

    public function publish(Exam $exam): JsonResponse
    {
        $exam->update(['status' => 'published']);

        return response()->json(['code' => 0, 'message' => '考试已发布']);
    }
}
