package cn.meowrain.aioj.backend.question.dto.chains;

import cn.meowrain.aioj.backend.framework.core.designpattern.chains.AbstractChianHandler;
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.dto.req.QuestionUpdateRequestDTO;
import cn.meowrain.aioj.backend.question.service.QuestionService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

/**
 * 题目更新时题目存在性校验
 */
@Slf4j
@Component
@RequiredArgsConstructor
public class QuestionUpdateExistVerifyChain implements AbstractChianHandler<QuestionUpdateRequestDTO> {

	private final QuestionService questionService;

	@Override
	public void handle(QuestionUpdateRequestDTO requestParam) {
		Long questionId = requestParam.getId();

		// 校验题目ID不为空
		if (questionId == null) {
			throw new ClientException("题目ID不能为空", ErrorCode.PARAMS_ERROR);
		}

		// 校验题目是否存在
		boolean exists = questionService.lambdaQuery()
			.eq(cn.meowrain.aioj.backend.question.dao.entity.Question::getId, questionId)
			.exists();

		if (!exists) {
			throw new ClientException("题目不存在，无法更新，题目ID: " + questionId, ErrorCode.NOT_FOUND_ERROR);
		}

		log.debug("题目更新存在性校验通过，题目ID: {}", questionId);
	}

	@Override
	public String mark() {
		return ChainMarkEnums.QUESTION_UPDATE_PARAM_VERIFY_CHAIN.getMark();
	}

	@Override
	public int getOrder() {
		return 10;
	}
}
