package com.izouma.nineth.service;

import com.izouma.nineth.domain.Follow;
import com.izouma.nineth.dto.PageQuery;
import com.izouma.nineth.repo.FollowRepo;
import com.izouma.nineth.repo.UserRepo;
import com.izouma.nineth.utils.JpaUtils;
import lombok.AllArgsConstructor;
import org.springframework.data.domain.Page;
import org.springframework.security.core.parameters.P;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
@AllArgsConstructor
public class FollowService {

    private FollowRepo followRepo;
    private UserRepo   userRepo;

    public Page<Follow> all(PageQuery pageQuery) {
        return followRepo.findAll(JpaUtils.toSpecification(pageQuery, Follow.class), JpaUtils.toPageRequest(pageQuery));
    }

    public void follow(Long userId, Long to) {
        List<Follow> list = followRepo.findByUserIdAndFollowUserId(userId, to);
        if (!list.isEmpty()) return;
        followRepo.save(Follow.builder()
                .userId(userId)
                .followUserId(to)
                .build());
        userRepo.updateFollows(userId);
        userRepo.updateFollowers(to);
    }

    public void unfollow(Long userId, Long to) {
        List<Follow> list = followRepo.findByUserIdAndFollowUserId(userId, to);
        if (!list.isEmpty()) {
            followRepo.deleteAll(list);
            userRepo.updateFollows(userId);
            userRepo.updateFollowers(to);
        }
    }

    boolean isFollow(Long userId, Long to) {
        return followRepo.findByUserIdAndFollowUserId(userId, to).size() > 0;
    }
}
