package cn.meowrain.aioj.backend.question.service.impl;

import cn.meowrain.aioj.backend.framework.core.errorcode.ErrorCode;
import cn.meowrain.aioj.backend.framework.core.exception.ClientException;
import cn.meowrain.aioj.backend.question.common.enums.ChainMarkEnums;
import cn.meowrain.aioj.backend.question.dao.entity.QuestionSubmit;
import cn.meowrain.aioj.backend.question.dao.mapper.QuestionSubmitMapper;
import cn.meowrain.aioj.backend.question.dto.chains.context.QuestionSubmitRequestParamVerifyContext;
import cn.meowrain.aioj.backend.question.dto.req.QuestionSubmitRequestDTO;
import cn.meowrain.aioj.backend.question.service.QuestionSubmitService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

/**
 * 题目提交服务实现
 */
@Slf4j
@Service
@RequiredArgsConstructor
public class QuestionSubmitServiceImpl extends ServiceImpl<QuestionSubmitMapper, QuestionSubmit> implements QuestionSubmitService {

	private final QuestionSubmitRequestParamVerifyContext submitChainContext;

    @Transactional(rollbackFor = Exception.class)
    @Override
    public Long createSubmit(QuestionSubmit questionSubmit) {
        return createSubmitWithChain(questionSubmit);
    }

	/**
	 * 使用责任链模式创建题目提交
	 */
	private Long createSubmitWithChain(QuestionSubmit questionSubmit) {
		// 将 QuestionSubmit 转换为 QuestionSubmitRequestDTO 用于责任链校验
		QuestionSubmitRequestDTO requestDTO = new QuestionSubmitRequestDTO();
		requestDTO.setQuestionId(questionSubmit.getQuestionId());
		requestDTO.setLanguage(questionSubmit.getLanguage());
		requestDTO.setCode(questionSubmit.getCode());

		// 执行责任链校验
		log.info("开始执行题目提交责任链校验，题目ID: {}", questionSubmit.getQuestionId());
		submitChainContext.handler(
			ChainMarkEnums.QUESTION_SUBMIT_REQ_PARAM_VERIFY_CHAIN.getMark(),
			requestDTO
		);
		log.info("题目提交责任链校验通过");

		// 校验通过，保存提交记录
		// 设置初始状态：0 - 待判题
		questionSubmit.setStatus(0);

		this.save(questionSubmit);
		return questionSubmit.getId();
	}

    @Override
    public Boolean updateSubmitStatus(QuestionSubmit questionSubmit) {
        return this.updateById(questionSubmit);
    }

    @Override
    public QuestionSubmit getSubmitById(Long submitId) {
        return this.getById(submitId);
    }
}
