package com.red.circle.other.infra.database.rds.service.user.user.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.user.user.ConfessionChanceDAO;
import com.red.circle.other.infra.database.rds.entity.user.user.ConfessionChance;
import com.red.circle.other.infra.database.rds.service.user.user.ConfessionChanceService;
import com.red.circle.tool.core.date.TimestampUtils;
import java.util.List;
import java.util.Objects;
import java.util.Optional;
import lombok.AllArgsConstructor;
import org.springframework.stereotype.Service;

/**
 * <p>
 * 告白机会 服务实现类.
 * </p>
 *
 * @author zongpubin on 2023-11-14 15:45
 */
@Service
@AllArgsConstructor
public class ConfessionChanceServiceImpl extends
    BaseServiceImpl<ConfessionChanceDAO, ConfessionChance> implements
    ConfessionChanceService {

  @Override
  public Long countConfessionChance(Long userId) {
    return Optional.of(query().eq(ConfessionChance::getUserId, userId)
        .eq(ConfessionChance::getConfessed, Boolean.FALSE)
        .gt(ConfessionChance::getExpiredTime, TimestampUtils.now())
        .count()).orElse(0L);
  }

  @Override
  public List<ConfessionChance> getUserConfessionChance(Long userId, Long lastId) {
    return query()
        .eq(ConfessionChance::getUserId, userId)
        .eq(ConfessionChance::getConfessed, Boolean.FALSE)
        .gt(ConfessionChance::getExpiredTime, TimestampUtils.now())
        .gt(Objects.nonNull(lastId), ConfessionChance::getId, lastId)
        .orderByAsc(ConfessionChance::getId)
        .last(PageConstant.DEFAULT_LIMIT)
        .list();
  }

  @Override
  public ConfessionChance getChanceById(Long id) {
    return query()
        .eq(ConfessionChance::getId, id)
        .eq(ConfessionChance::getConfessed, Boolean.FALSE)
        .gt(ConfessionChance::getExpiredTime, TimestampUtils.now())
        .last(PageConstant.LIMIT_ONE)
        .getOne();
  }

  @Override
  public void updateChanceById(Long id) {
    update()
        .set(ConfessionChance::getConfessed, Boolean.TRUE)
        .eq(ConfessionChance::getId, id)
        .execute();
  }
}
