package com.competition.modules.biz.homework.controller;

import com.competition.common.enums.ErrorCode;
import com.competition.common.exception.BusinessException;
import com.competition.common.result.Result;
import com.competition.common.util.SecurityUtil;
import com.competition.modules.biz.homework.dto.CreateHomeworkScoreDto;
import com.competition.modules.biz.homework.entity.BizHomeworkScore;
import com.competition.modules.biz.homework.entity.BizHomeworkSubmission;
import com.competition.modules.biz.homework.service.IHomeworkScoreService;
import com.competition.modules.biz.homework.service.IHomeworkSubmissionService;
import com.competition.security.annotation.RequirePermission;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import jakarta.validation.Valid;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.*;

@Slf4j
@Tag(name = "作业评分")
@RestController
@RequestMapping("/homework/scores")
@RequiredArgsConstructor
public class HomeworkScoreController {

    private final IHomeworkScoreService homeworkScoreService;
    private final IHomeworkSubmissionService homeworkSubmissionService;

    @PostMapping
    @RequirePermission("homework:update")
    @Operation(summary = "创建评分")
    public Result<BizHomeworkScore> create(@Valid @RequestBody CreateHomeworkScoreDto dto) {
        Long reviewerId = SecurityUtil.getCurrentUserId();
        Long tenantId = SecurityUtil.getCurrentTenantId();
        return Result.success(homeworkScoreService.create(dto, reviewerId, tenantId));
    }

    @PostMapping("/{submissionId}/violation")
    @RequirePermission("homework:update")
    @Operation(summary = "标记违规")
    public Result<Void> markViolation(@PathVariable Long submissionId) {
        log.info("标记作业提交违规，提交ID：{}", submissionId);

        BizHomeworkSubmission submission = homeworkSubmissionService.getById(submissionId);
        if (submission == null) {
            throw BusinessException.of(ErrorCode.NOT_FOUND, "作业提交不存在");
        }

        submission.setStatus("violation");
        homeworkSubmissionService.updateById(submission);
        log.info("作业提交已标记为违规，提交ID：{}", submissionId);
        return Result.success();
    }

    @PostMapping("/{submissionId}/reset")
    @RequirePermission("homework:update")
    @Operation(summary = "重置评分状态")
    public Result<Void> resetStatus(@PathVariable Long submissionId) {
        log.info("重置作业提交评分状态，提交ID：{}", submissionId);

        BizHomeworkSubmission submission = homeworkSubmissionService.getById(submissionId);
        if (submission == null) {
            throw BusinessException.of(ErrorCode.NOT_FOUND, "作业提交不存在");
        }

        submission.setStatus("pending");
        submission.setTotalScore(null);
        homeworkSubmissionService.updateById(submission);
        log.info("作业提交评分状态已重置，提交ID：{}", submissionId);
        return Result.success();
    }
}
