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

import cn.meowrain.aioj.backend.question.dao.entity.Question;
import cn.meowrain.aioj.backend.question.dao.mapper.QuestionMapper;
import cn.meowrain.aioj.backend.question.dto.req.QuestionQueryRequestDTO;
import cn.meowrain.aioj.backend.question.service.QuestionService;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import lombok.RequiredArgsConstructor;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;

/**
 * 题目服务实现
 */
@Service
@RequiredArgsConstructor
public class QuestionServiceImpl extends ServiceImpl<QuestionMapper, Question> implements QuestionService {

	@Override
	public Long createQuestion(Question question) {
		this.save(question);
		return question.getId();
	}

	@Override
	public Boolean updateQuestion(Question question) {
		return this.updateById(question);
	}

	@Override
	public Boolean deleteQuestion(Long questionId) {
		return this.removeById(questionId);
	}

	@Override
	public Question getQuestionById(Long questionId) {
		return this.getById(questionId);
	}

	@Override
	public Question getQuestionByIdInner(Long questionId) {
		return this.getById(questionId);
	}

	@Override
	public Page<Question> listQuestions(QuestionQueryRequestDTO request) {
		LambdaQueryWrapper<Question> wrapper = new LambdaQueryWrapper<>();

		// ID 精确查询
		if (request.getId() != null) {
			wrapper.eq(Question::getId, request.getId());
		}

		// 标题模糊查询
		if (StringUtils.isNotBlank(request.getTitle())) {
			wrapper.like(Question::getTitle, request.getTitle());
		}

		// 难度精确查询
		if (StringUtils.isNotBlank(request.getDifficulty())) {
			wrapper.eq(Question::getDifficulty, request.getDifficulty());
		}

		// 创建者 ID 查询
		if (request.getUserId() != null) {
			wrapper.eq(Question::getUserId, request.getUserId());
		}

		// 排序
		if (StringUtils.isNotBlank(request.getSortField())) {
			if ("asc".equalsIgnoreCase(request.getSortOrder())) {
				wrapper.orderByAsc(Question::getCreateTime);
			} else {
				wrapper.orderByDesc(Question::getCreateTime);
			}
		} else {
			wrapper.orderByDesc(Question::getCreateTime);
		}

		// 直接使用 request 作为分页对象
		return this.page(request, wrapper);
	}
}
