package com.red.circle.external.infra.database.redis.service.impl;

import com.red.circle.component.redis.service.RedisService;
import com.red.circle.external.infra.database.redis.key.LiveUserAgoraKey;
import com.red.circle.external.infra.database.redis.service.UserAgoraTokenCacheService;
import com.red.circle.tool.crypto.SecurityUtils;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;

import java.util.Objects;
import java.util.concurrent.TimeUnit;

/**
 * UserAgoraToken缓存服务.
 *
 * @author lixiaofei on 2024/9/4
 */
@Service
@RequiredArgsConstructor
public class UserAgoraTokenCacheServiceImpl implements UserAgoraTokenCacheService {

  private final RedisService redisService;
  private static final long CACHE_TIME = 7200;

  @Override
  public void remove(Long userId, Long roomId) {
    redisService.delete(getUserAgoraTokenKey(userId, roomId));
  }

  @Override
  public void save(String agoraToken, Long userId, Long roomId) {
    redisService.setIfAbsent(getUserAgoraTokenKey(userId, roomId), agoraToken, CACHE_TIME, TimeUnit.SECONDS);
  }

  @Override
  public String getUserAgoraToken(Long userId, Long roomId) {
    return redisService.getString(getUserAgoraTokenKey(userId, roomId));
  }

  @Override
  public void removeRoom(Long userId, Long roomId) {
    redisService.delete(getUserAgoraTokenRoomKey(userId, roomId));
  }

  @Override
  public void saveRoom(String agoraToken, Long userId, Long roomId) {
    redisService.setIfAbsent(getUserAgoraTokenRoomKey(userId, roomId), agoraToken, CACHE_TIME, TimeUnit.SECONDS);
  }

  @Override
  public String getUserAgoraTokenRoom(Long userId, Long roomId) {
    return redisService.getString(getUserAgoraTokenRoomKey(userId, roomId));
  }

  @Override
  public String getUserToken(Long userId) {
    return redisService.getString(getAccessTokenCacheKey(userId));
  }

  private String getUserAgoraTokenKey(Long userId, Long roomId) {
    return LiveUserAgoraKey.USER_AGORA_TOKEN.getKey(userId, roomId);
  }

  private String getUserAgoraTokenRoomKey(Long userId, Long roomId) {
    return LiveUserAgoraKey.ROOM_AGORA_TOKEN.getKey(userId, roomId);
  }

  String ACCESS_TOKEN = "token";

  private String getAccessTokenCacheKey(Long userId) {
    return ACCESS_TOKEN + ":" + SecurityUtils.md5(Objects.toString(userId));
  }

  @Override
  public void saveUserAccount(String account, Long userId) {
    redisService.setIfAbsent(getUserAccountKey(userId), account);
  }

  @Override
  public String getUserAccount(Long userId) {
    return redisService.getString(getUserAccountKey(userId));
  }

  private String getUserAccountKey(Long userId) {
    return LiveUserAgoraKey.USER_ACCOUNT.getKey(userId);
  }

}
