package dev.awesomedev.mirim.web;

import dev.awesomedev.mirim.domain.QuizQuestion;
import dev.awesomedev.mirim.domain.User;
import dev.awesomedev.mirim.service.AuthService;
import dev.awesomedev.mirim.service.QuizService;
import org.springframework.security.core.Authentication;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.Map;

/**
 * 이 파일이 하는 일:
 * 코스 퀴즈 API — 문항 조회(정답 제외!), 제출·채점, 내 결과 요약.
 */
@RestController
@RequestMapping("/api/quiz")
public class QuizController {

    private final QuizService quizService;
    private final AuthService authService;

    public QuizController(QuizService quizService, AuthService authService) {
        this.quizService = quizService;
        this.authService = authService;
    }

    /** 문항 응답 — answerIndex와 explanation이 "없는" 것이 이 DTO의 존재 이유다 */
    public record QuestionResponse(Long id, String question, List<String> options) {
        static QuestionResponse from(QuizQuestion question) {
            return new QuestionResponse(question.getId(), question.getQuestion(),
                    List.of(question.getOption1(), question.getOption2(),
                            question.getOption3(), question.getOption4()));
        }
    }

    /** GET /api/quiz/{slug} — 코스의 문항 목록 (정답 없이) */
    @GetMapping("/{slug}")
    public List<QuestionResponse> questions(@PathVariable String slug,
                                            Authentication authentication) {
        authService.requireUser(authentication);
        return quizService.questionsFor(slug).stream()
                .map(QuestionResponse::from)
                .toList();
    }

    /** 제출 요청 — {answers: {문항id: 고른 보기 번호(0~3)}} */
    public record SubmitRequest(Map<Long, Integer> answers) {
    }

    /** POST /api/quiz/{slug}/submit — 채점하고 기록을 남긴 뒤, 정답·해설과 함께 결과 반환 */
    @PostMapping("/{slug}/submit")
    public QuizService.GradeResult submit(@PathVariable String slug,
                                          @RequestBody SubmitRequest request,
                                          Authentication authentication) {
        User user = authService.requireUser(authentication);
        return quizService.grade(user, slug, request.answers());
    }

    /** GET /api/quiz/results/me — 코스별 내 최고 점수·응시 횟수 */
    @GetMapping("/results/me")
    public List<QuizService.ResultSummary> myResults(Authentication authentication) {
        User user = authService.requireUser(authentication);
        return quizService.summaryFor(user);
    }
}
