package dev.awesomedev.mirim.web;

import dev.awesomedev.mirim.domain.Submission;
import dev.awesomedev.mirim.domain.User;
import dev.awesomedev.mirim.service.AuthService;
import dev.awesomedev.mirim.service.SubmissionService;
import dev.awesomedev.mirim.web.dto.SubmissionRequest;
import dev.awesomedev.mirim.web.dto.SubmissionResponse;
import org.springframework.http.HttpStatus;
import org.springframework.security.core.Authentication;
import org.springframework.web.bind.annotation.*;

import java.util.List;

/**
 * 이 파일이 하는 일:
 * 과제 제출(생성/재제출)과 내 제출물 조회 API를 제공하는 컨트롤러다.
 */
@RestController
@RequestMapping("/api/submissions")
public class SubmissionController {

    private final SubmissionService submissionService;
    private final AuthService authService;

    public SubmissionController(SubmissionService submissionService, AuthService authService) {
        this.submissionService = submissionService;
        this.authService = authService;
    }

    /** GET /api/submissions/me — 내 제출물 목록 (최신순) */
    @GetMapping("/me")
    public List<SubmissionResponse> mySubmissions(Authentication authentication) {
        User user = authService.requireUser(authentication);
        return submissionService.mySubmissions(user).stream()
                .map(SubmissionResponse::from)
                .toList();
    }

    /**
     * POST /api/submissions — 과제 제출. 이미 낸 과제면 내용을 갱신한다.
     * 학습 포인트: "자원 생성"이라 REST 관례대로 201 Created를 돌려준다.
     */
    @PostMapping
    @ResponseStatus(HttpStatus.CREATED)
    public SubmissionResponse submit(@RequestBody SubmissionRequest submissionRequest,
                                     Authentication authentication) {
        User user = authService.requireUser(authentication);
        Submission submission = submissionService.submitOrUpdate(
                user, submissionRequest.assignmentId(),
                submissionRequest.content(), submissionRequest.link());
        return SubmissionResponse.from(submission);
    }
}
