package cn.meowrain.aioj.backend.question.controller;

import cn.meowrain.aioj.backend.framework.core.errorcode.ErrorCode;
import cn.meowrain.aioj.backend.framework.core.web.Result;
import cn.meowrain.aioj.backend.framework.core.web.Results;
import cn.meowrain.aioj.backend.question.dao.entity.QuestionSubmit;
import cn.meowrain.aioj.backend.question.dto.req.QuestionSubmitRequestDTO;
import cn.meowrain.aioj.backend.question.service.QuestionSubmitService;
import com.alibaba.csp.sentinel.annotation.SentinelResource;
import com.alibaba.csp.sentinel.slots.block.BlockException;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.tags.Tag;
import jakarta.validation.Valid;
import lombok.RequiredArgsConstructor;
import org.springframework.beans.BeanUtils;
import org.springframework.web.bind.annotation.*;

/**
 * 题目提交管理控制器 - RESTful API
 */
@RequiredArgsConstructor
@RestController
@RequestMapping("/v1/question-submits")
@Tag(name = "题目提交管理", description = "题目提交相关接口")
public class QuestionSubmitController {

	private final QuestionSubmitService questionSubmitService;

	/**
	 * 提交代码
	 * POST /v1/question-submits
	 */
	@PostMapping
	@Operation(summary = "提交代码", description = "用户提交代码答案")
	@SentinelResource(value = "submit-question",blockHandler = "handleException")
	public Result<Long> submitQuestion(
			@Parameter(description = "提交信息", required = true)
			@RequestBody @Valid QuestionSubmitRequestDTO request) {
		QuestionSubmit questionSubmit = new QuestionSubmit();
		BeanUtils.copyProperties(request, questionSubmit);
		Long submitId = questionSubmitService.createSubmit(questionSubmit);
		return Results.success(submitId);
	}

	public Result<Void> handleException(QuestionSubmitRequestDTO request, BlockException ex) {
		System.out.println("被限流了: " + ex.getClass().getCanonicalName());

		// 假设你的 Results 工具类支持返回错误信息
		// 这里的 code (比如 429) 和 message 根据你的 Result 结构来定
		return Results.failure(ErrorCode.API_REQUEST_ERROR.code(),"系统繁忙，请稍后再试！（这是自定义的限流提示）");
	}

	/**
	 * 获取提交详情
	 * GET /v1/question-submits/{id}
	 */
	@GetMapping("/{id}")
	@Operation(summary = "获取提交详情", description = "根据ID获取提交详情")
	public Result<QuestionSubmit> getSubmit(
			@Parameter(description = "提交ID", required = true)
			@PathVariable("id") Long id) {
		QuestionSubmit submit = questionSubmitService.getSubmitById(id);
		return Results.success(submit);
	}

	/**
	 * 内部接口：更新提交状态
	 * PATCH /v1/question-submits/{id}/status
	 */
	@PatchMapping("/{id}/status")
	@Operation(summary = "更新提交状态", description = "判题服务更新提交状态（内部接口）")
	public Result<Void> updateSubmitStatus(
			@Parameter(description = "提交ID", required = true)
			@PathVariable("id") Long id,
			@Parameter(description = "状态信息", required = true)
			@RequestBody QuestionSubmit questionSubmit) {
		questionSubmit.setId(id);
		questionSubmitService.updateSubmitStatus(questionSubmit);
		return Results.success();
	}
}
