package com.luojia_channel.modules.post.utils;

import cn.hutool.core.util.StrUtil;
import com.luojia_channel.common.exception.PostException;
import com.luojia_channel.common.exception.UserException;
import com.luojia_channel.common.utils.UserContext;
import com.luojia_channel.modules.post.dto.req.CommentSaveDTO;
import com.luojia_channel.modules.post.dto.req.PostSaveDTO;
import com.luojia_channel.modules.post.entity.Comment;
import com.luojia_channel.modules.post.entity.Post;
import com.luojia_channel.modules.post.mapper.CommentMapper;
import com.luojia_channel.modules.post.mapper.PostMapper;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;

@Component
@RequiredArgsConstructor
public class ValidatePostUtil {

    private final PostMapper postMapper;

    private final CommentMapper commentMapper;

    public void validatePost(PostSaveDTO postSaveDTO) {
        // 非空字段检验
        if (StrUtil.isBlank(postSaveDTO.getTitle())) {
            throw new PostException("标题不能为空");
        }
        if (StrUtil.isBlank(postSaveDTO.getImage())) {
            throw new PostException("未设置图片");
        }
        if (StrUtil.isBlank(postSaveDTO.getContent())) {
            throw new PostException("内容不能为空");
        }
        if (postSaveDTO.getCategoryId() == null || postSaveDTO.getCategoryId() <= 0) {
            throw new PostException("分区不合法");
        }
    }

    public void validatePostOwnership(Long id){
        Long userId = UserContext.getUserId();
        if(userId == null){
            throw new UserException("用户未登录");
        }
        if(id == null){
            throw new PostException("传入id不能为空");
        }
        Post post = postMapper.selectById(id);
        if(post == null){
            throw new PostException("帖子不存在");
        }
        if(!userId.equals(post.getUserId())){
            throw new PostException("你无权操作他人的帖子");
        }
    }

    public void validateComment(CommentSaveDTO commentSaveDTO) {
        if (StrUtil.isBlank(commentSaveDTO.getContent())) {
            throw new PostException("内容不能为空");
        }
        if (commentSaveDTO.getPostId() == null || commentSaveDTO.getPostId() < 0){
            throw new PostException("帖子id不合法");
        }
        if(commentSaveDTO.getParentCommentId() != null && commentSaveDTO.getParentCommentId() < 0){
            throw new PostException("父评论id不合法");
        }
    }

    public void validateCommentOwnership(Long id) {
        Long userId = UserContext.getUserId();
        if(userId == null){
            throw new UserException("用户未登录");
        }
        if(id == null){
            throw new PostException("传入id不能为空");
        }
        Comment comment = commentMapper.selectById(id);
        if(comment == null){
            throw new PostException("评论不存在");
        }
        if(!userId.equals(comment.getUserId())){
            throw new PostException("你无权操作他人的评论");
        }
    }
}
