package top.tqx.demo_1.controller;

import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import jakarta.servlet.http.HttpServletRequest;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import top.tqx.demo_1.common.Result;
import top.tqx.demo_1.dto.*;
import top.tqx.demo_1.enums.AnswerType;

import java.util.List;

@Slf4j
@RestController
@RequestMapping("/formal-exam")
@Tag(name = "正式考试", description = "正式考试相关接口，仅供被分配了正式试卷的用户使用")
public class FormalExamController extends BaseController {

    @Autowired
    private top.tqx.demo_1.service.ExamRecordService examRecordService;

    @Operation(summary = "开始正式考试", description = "通过试卷ID开始正式考试，系统自动查找或创建考试记录，返回试卷题目内容")
    @PostMapping("/paper/{paperId}/start")
    public Result<ExamRecordResponse> startExamByPaperId(
            @PathVariable String paperId,
            HttpServletRequest httpRequest) {
        try {
            Long userId = getCurrentUserId(httpRequest);
            ExamRecordResponse response = examRecordService.startExamByPaperId(paperId, userId, AnswerType.FORMAL_EXAM.getCode());
            return Result.success(response);
        } catch (Exception e) {
            log.error("开始考试失败: {}", e.getMessage());
            return Result.error(500, e.getMessage());
        }
    }

    @Operation(summary = "获取正式考试结果", description = "获取正式考试的完整结果，包含每题得分和反馈")
    @GetMapping("/record/{recordId}/result")
    public Result<ExamRecordResponse> getExamResult(
            @PathVariable String recordId,
            HttpServletRequest httpRequest) {
        try {
            Long userId = getCurrentUserId(httpRequest);
            ExamRecordResponse response = examRecordService.getRecordById(recordId);
            
            if (response == null) {
                return Result.error(404, "记录不存在");
            }
            
            if (!response.getUserId().equals(userId)) {
                return Result.error(403, "无权查看此记录");
            }
            
            return Result.success(response);
        } catch (Exception e) {
            log.error("获取考试结果失败: {}", e.getMessage());
            return Result.error(500, e.getMessage());
        }
    }
}
