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

import com.fasterxml.jackson.core.type.TypeReference;
import com.red.circle.component.redis.service.RedisService;
import com.red.circle.tool.core.collection.CollectionUtils;
import com.red.circle.other.infra.database.cache.key.user.SysRegionKey;
import com.red.circle.other.infra.database.cache.service.user.SysRegionCacheService;
import com.red.circle.other.infra.database.mongo.entity.user.region.SysRegionConfig;
import com.red.circle.other.infra.database.mongo.service.user.region.SysRegionConfigService;
import java.util.List;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;

/**
 * 系统分区缓存 实现.
 *
 * @author pengliang on 2023/9/25
 */
@Service
@RequiredArgsConstructor
public class SysRegionCacheServiceImpl implements SysRegionCacheService {

  private final RedisService redisService;
  private final SysRegionConfigService sysRegionConfigService;

  @Override
  public List<SysRegionConfig> getCache(String sysOrigin) {

    List<SysRegionConfig> sysRegionConfigs = redisService.hashGet(
        SysRegionKey.HASH.getKey(),
        sysOrigin,
        new TypeReference<>() {
        });

    if (CollectionUtils.isNotEmpty(sysRegionConfigs)) {
      return sysRegionConfigs;
    }

    List<SysRegionConfig> newRegionConfigs = sysRegionConfigService.listAvailable(sysOrigin);

    if (CollectionUtils.isNotEmpty(newRegionConfigs)) {
      redisService.hashPut(SysRegionKey.HASH.getKey(), sysOrigin, newRegionConfigs);
    }

    return newRegionConfigs;
  }

  @Override
  public void remove(String sysOrigin) {
    redisService.hashDelete(SysRegionKey.HASH.getKey(), sysOrigin);
  }

  @Override
  public void remove() {
    redisService.delete(SysRegionKey.HASH.getKey());
  }

}
