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

import com.xindazhou.business.dal.community.dataobject.follow.FollowDO;
import com.xindazhou.business.dal.community.mysql.follow.FollowMapper;
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.BAD_REQUEST;

/**
 * 关注 Service 实现类
 *
 * @author xindazhou
 */
@Service("communityFollowServiceImpl")
@Slf4j
@Validated
public class FollowServiceImpl implements FollowService {

    @Resource
    private FollowMapper followMapper;

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Boolean toggleFollow(Long followUserId) {
        // 获取当前登录用户
        Long userId = SecurityFrameworkUtils.getLoginUserId();

        // 不能关注自己
        if (userId.equals(followUserId)) {
            throw exception(BAD_REQUEST, "不能关注自己");
        }

        // 查询是否已关注
        FollowDO existingFollow = followMapper.selectByUserIdAndFollowUserId(userId, followUserId);

        if (existingFollow != null) {
            // 已关注，取消关注
            followMapper.deleteById(existingFollow.getId());
            return false;
        } else {
            // 未关注，执行关注
            FollowDO follow = new FollowDO();
            follow.setUserId(userId);
            follow.setFollowUserId(followUserId);
            follow.setCreateTime(LocalDateTime.now());
            followMapper.insert(follow);
            return true;
        }
    }

    @Override
    public Boolean isFollowed(Long followUserId) {
        Long userId = SecurityFrameworkUtils.getLoginUserId();
        if (userId == null) {
            return false;
        }
        FollowDO follow = followMapper.selectByUserIdAndFollowUserId(userId, followUserId);
        return follow != null;
    }

    @Override
    public Long getFollowCount(Long userId) {
        return followMapper.selectFollowCount(userId);
    }

    @Override
    public Long getFansCount(Long userId) {
        return followMapper.selectFansCount(userId);
    }

}

