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

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 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 = "用户提交代码答案")
	public Result<Long> submitQuestion(
			@Parameter(description = "提交信息", required = true)
			@RequestBody @Valid QuestionSubmitRequestDTO request) {
		QuestionSubmit questionSubmit = new QuestionSubmit();
		BeanUtils.copyProperties(request, questionSubmit);
		// 设置初始状态为待判题
		questionSubmit.setStatus(0);
		Long submitId = questionSubmitService.createSubmit(questionSubmit);
		return Results.success(submitId);
	}

	/**
	 * 获取提交详情
	 * 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();
	}
}
