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

/**
 * 考试作答控制器
 */
class AttemptController extends Controller
{
    public function answer(Request $request, Attempt $attempt): JsonResponse
    {
        $validated = $request->validate([
            'question_id' => 'required|exists:questions,id',
            'answer' => 'required|string',
        ]);

        AttemptAnswer::updateOrCreate(
            [
                'attempt_id' => $attempt->id,
                'question_id' => $validated['question_id'],
            ],
            ['answer' => $validated['answer']]
        );

        return response()->json(['code' => 0, 'message' => '答案已保存']);
    }

    public function submit(Request $request, Attempt $attempt): JsonResponse
    {
        // 客观题自动阅卷
        $answers = $attempt->answers()->with('question')->get();
        $totalScore = 0;

        foreach ($answers as $answer) {
            if ($answer->question->type->isObjective()) {
                $isCorrect = $answer->answer === $answer->question->answer;
                $answer->update([
                    'is_correct' => $isCorrect,
                    'score' => $isCorrect ? $answer->question->score : 0,
                ]);
                $totalScore += $isCorrect ? $answer->question->score : 0;
            }
        }

        $attempt->update([
            'score' => $totalScore,
            'status' => 'submitted',
            'submitted_at' => now(),
        ]);

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