package com.xindazhou.business.service.community.like;

import com.xindazhou.business.dal.community.dataobject.comment.CommentDO;
import com.xindazhou.business.dal.community.dataobject.like.LikeDO;
import com.xindazhou.business.dal.community.dataobject.post.PostDO;
import com.xindazhou.business.dal.community.mysql.comment.CommunityCommentMapper;
import com.xindazhou.business.dal.community.mysql.like.LikeMapper;
import com.xindazhou.business.dal.community.mysql.post.CommunityPostMapper;
import com.xindazhou.framework.security.core.util.SecurityFrameworkUtils;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.validation.annotation.Validated;

import java.time.LocalDateTime;

import static com.xindazhou.framework.common.exception.util.ServiceExceptionUtil.exception;
import static com.xindazhou.framework.common.exception.enums.GlobalErrorCodeConstants.NOT_FOUND;

/**
 * 点赞 Service 实现类
 *
 * @author xindazhou
 */
@Service("communityLikeServiceImpl")
@Slf4j
@Validated
public class LikeServiceImpl implements LikeService {

    @Resource
    private LikeMapper likeMapper;

    @Resource
    private CommunityPostMapper communityPostMapper;

    @Resource
    private CommunityCommentMapper commentMapper;

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Boolean toggleLike(Integer targetType, Long targetId) {
        // 校验目标对象存在
        validateTargetExists(targetType, targetId);

        // 获取当前登录用户
        Long userId = SecurityFrameworkUtils.getLoginUserId();

        // 查询是否已点赞
        LikeDO existingLike = likeMapper.selectByUserIdAndTarget(userId, targetType, targetId);

        if (existingLike != null) {
            // 已点赞，取消点赞
            likeMapper.deleteById(existingLike.getId());
            decrementLikeCount(targetType, targetId);
            return false;
        } else {
            // 未点赞，执行点赞
            LikeDO like = new LikeDO();
            like.setUserId(userId);
            like.setTargetType(targetType);
            like.setTargetId(targetId);
            like.setCreateTime(LocalDateTime.now());
            likeMapper.insert(like);
            incrementLikeCount(targetType, targetId);
            return true;
        }
    }

    @Override
    public Boolean isLiked(Integer targetType, Long targetId) {
        Long userId = SecurityFrameworkUtils.getLoginUserId();
        LikeDO like = likeMapper.selectByUserIdAndTarget(userId, targetType, targetId);
        return like != null;
    }

    @Override
    public Long getLikeCount(Integer targetType, Long targetId) {
        return likeMapper.selectCountByTarget(targetType, targetId);
    }

    /**
     * 增加点赞数
     */
    private void incrementLikeCount(Integer targetType, Long targetId) {
        if (targetType == 1) {
            // 帖子
            PostDO post = communityPostMapper.selectById(targetId);
            if (post != null) {
                post.setLikeCount(post.getLikeCount() + 1);
                communityPostMapper.updateById(post);
            }
        } else if (targetType == 2) {
            // 评论
            CommentDO comment = commentMapper.selectById(targetId);
            if (comment != null) {
                comment.setLikeCount(comment.getLikeCount() + 1);
                commentMapper.updateById(comment);
            }
        }
    }

    /**
     * 减少点赞数
     */
    private void decrementLikeCount(Integer targetType, Long targetId) {
        if (targetType == 1) {
            // 帖子
            PostDO post = communityPostMapper.selectById(targetId);
            if (post != null && post.getLikeCount() > 0) {
                post.setLikeCount(post.getLikeCount() - 1);
                communityPostMapper.updateById(post);
            }
        } else if (targetType == 2) {
            // 评论
            CommentDO comment = commentMapper.selectById(targetId);
            if (comment != null && comment.getLikeCount() > 0) {
                comment.setLikeCount(comment.getLikeCount() - 1);
                commentMapper.updateById(comment);
            }
        }
    }

    /**
     * 校验目标对象存在
     */
    private void validateTargetExists(Integer targetType, Long targetId) {
        if (targetType == 1) {
            // 帖子
            PostDO post = communityPostMapper.selectById(targetId);
            if (post == null) {
                throw exception(NOT_FOUND, "帖子不存在");
            }
        } else if (targetType == 2) {
            // 评论
            CommentDO comment = commentMapper.selectById(targetId);
            if (comment == null) {
                throw exception(NOT_FOUND, "评论不存在");
            }
        } else {
            throw exception(NOT_FOUND, "不支持的目标类型");
        }
    }

}

