package cn.reghao.tnb.user.app.service;

import cn.reghao.tnb.user.api.dto.UserCard;
import cn.reghao.tnb.user.app.db.mapper.UserRelationMapper;
import cn.reghao.tnb.user.app.model.po.UserRelation;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.stream.Collectors;

/**
 * @author reghao
 * @date 2023-02-02 14:52:58
 */
@Service
public class UserRelationService {
    private final UserRelationMapper userRelationMapper;
    private final UserProfileService userProfileService;

    public UserRelationService(UserRelationMapper userRelationMapper, UserProfileService userProfileService) {
        this.userRelationMapper = userRelationMapper;
        this.userProfileService = userProfileService;
    }

    public boolean isFollowing(long loginUserId, long userId) {
        return userRelationMapper.findRelation(loginUserId, userId) != null;
    }

    public void followUser(long userId, long followingId) {
        if (userId == followingId) {
            return;
        }

        UserRelation userRelation = userRelationMapper.findRelation(userId, followingId);
        if (userRelation != null) {
            return;
        }

        userRelation = new UserRelation(userId, followingId);
        userRelationMapper.save(userRelation);
    }

    public void unfollowUser(long userId, long followingId) {
        if (userId == followingId) {
            return;
        }
        userRelationMapper.deleteByUserRelation(userId, followingId);
    }

    public List<UserCard> getFollowerCards(long userId) {
        List<Long> followerIds = userRelationMapper.findUserFollowers(userId);
        return followerIds.stream().map(userProfileService::getUserCard).collect(Collectors.toList());
    }

    public List<UserCard> getFollowingCards(long userId) {
        List<Long> followingIds = userRelationMapper.findUserFollowings(userId);
        return followingIds.stream().map(userProfileService::getUserCard).collect(Collectors.toList());
    }
}
