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

import com.red.circle.component.redis.service.RedisService;
import com.red.circle.other.infra.database.cache.service.team.BdTeamCacheService;
import java.util.Objects;
import java.util.stream.Stream;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;

/**
 * BD 团队相关缓存服务实现.
 */
@Service
@RequiredArgsConstructor
public class BdTeamCacheServiceImpl implements BdTeamCacheService {

  private static final String BD_CENTER_LEADER_KEY = "bdcenter:BDLEADER:%d";
  private static final String BD_CENTER_BD_KEY = "bdcenter:BD:%d";
  private static final String BD_TEAM_LEADER_KEY = "bdteam:BD_LEADER:%d";
  private static final String BD_TEAM_BD_KEY = "bdteam:BD:%d";
  private static final String BD_TEAM_SUMMARY_KEY = "bdteam:summary:%d";

  private final RedisService redisService;

  @Override
  public void clearLeaderRelatedCaches(Long leaderUserId) {
    if (Objects.isNull(leaderUserId)) {
      return;
    }

    delete(
        BD_CENTER_LEADER_KEY.formatted(leaderUserId),
        BD_TEAM_LEADER_KEY.formatted(leaderUserId),
        BD_TEAM_SUMMARY_KEY.formatted(leaderUserId)
    );
  }

  @Override
  public void clearBdRelatedCaches(Long bdUserId) {
    if (Objects.isNull(bdUserId)) {
      return;
    }

    delete(
        BD_CENTER_BD_KEY.formatted(bdUserId),
        BD_TEAM_BD_KEY.formatted(bdUserId),
        BD_TEAM_SUMMARY_KEY.formatted(bdUserId)
    );
  }

  @Override
  public void clearRelationChangeCaches(Long oldLeaderUserId, Long newLeaderUserId, Long bdUserId) {
    Stream.of(oldLeaderUserId, newLeaderUserId)
        .filter(Objects::nonNull)
        .distinct()
        .forEach(this::clearLeaderRelatedCaches);
    clearBdRelatedCaches(bdUserId);
  }

  private void delete(String... keys) {
    for (String key : keys) {
      redisService.delete(key);
    }
  }
}
