package com.red.circle.other.infra.database.cache.service.user.impl;


import com.red.circle.component.redis.service.RedisService;
import com.red.circle.tool.core.date.ZonedDateTimeAsiaRiyadhUtils;
import com.red.circle.other.infra.database.cache.service.user.UserAccountAuthCacheService;
import java.util.Objects;
import java.util.Optional;
import java.util.concurrent.TimeUnit;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;

/**
 * 账号密码登录
 *
 * @author zongpubin on 2023/9/13
 */
@Service
@RequiredArgsConstructor
public class UserAccountAuthCacheServiceImpl implements UserAccountAuthCacheService {

  private final RedisService redisService;

  @Override
  public void recordAccountAuth(Long userId) {

    if (Objects.isNull(userId)) {
      return;
    }

    String key = "ACCOUNT_LOGIN_TIME" + ZonedDateTimeAsiaRiyadhUtils.nowDateToInt() + "_" + userId;
    redisService.increment(key, 1l, 3, TimeUnit.DAYS);
  }

  @Override
  public Integer getAccountAuthTimes(Long userId) {
    if (Objects.isNull(userId)) {
      return 0;
    }

    String key = "ACCOUNT_LOGIN_TIME" + ZonedDateTimeAsiaRiyadhUtils.nowDateToInt() + "_" + userId;
    return Optional.ofNullable(redisService.getStringToInteger(key)).orElse(0);
  }

  @Override
  public void deleteByUserId(Long userId) {
    String key = "ACCOUNT_LOGIN_TIME" + ZonedDateTimeAsiaRiyadhUtils.nowDateToInt() + "_" + userId;
    redisService.delete(key);
  }
}

