package com.red.circle.other.infra.database.rds.service.dynamic.impl;


import com.red.circle.framework.mybatis.constant.PageConstant;
import com.red.circle.framework.mybatis.service.impl.BaseServiceImpl;
import com.red.circle.other.infra.database.rds.dao.dynamic.UserThumbsUpDAO;
import com.red.circle.other.infra.database.rds.entity.dynamic.UserThumbsUp;
import com.red.circle.other.infra.database.rds.service.dynamic.UserThumbsUpService;
import java.util.Objects;
import java.util.Optional;
import org.springframework.dao.DuplicateKeyException;
import org.springframework.stereotype.Service;

/**
 * <p>
 * 用户点赞列表 服务实现类.
 * </p>
 *
 * @author zongpubin on 2023-04-06 11:41
 */
@Service
public class UserThumbsUpServiceImpl extends
    BaseServiceImpl<UserThumbsUpDAO, UserThumbsUp> implements
    UserThumbsUpService {

  @Override
  public boolean checkExist(Long userId, Long thumbsUpId) {
    return Optional.ofNullable(query()
            .select(UserThumbsUp::getId)
            .eq(UserThumbsUp::getUserId, userId)
            .eq(UserThumbsUp::getThumbsUpUserId, thumbsUpId)
            .last(PageConstant.LIMIT_ONE)
            .getOne()).map(thumbsUp -> Objects.nonNull(thumbsUp.getId()))
        .orElse(Boolean.FALSE);
  }

  @Override
  public boolean notExistsAdd(Long userId, Long thumbsUpId) {
    try {
      save(new UserThumbsUp()
          .setThumbsUpUserId(thumbsUpId)
          .setUserId(userId)
      );
      return true;
    } catch (DuplicateKeyException ignore) {
      // ignore
    }
    return false;
  }

  @Override
  public long countThumbsUp(Long thumbsUpId) {
    if (Objects.isNull(thumbsUpId)) {
      return 0L;
    }
    return query().eq(UserThumbsUp::getThumbsUpUserId, thumbsUpId).count();
  }
}
