package net.northking.cctp.common.saas.config;

import net.northking.cctp.common.saas.cache.SaaSAppDataSourceClusterCache;
import net.northking.cctp.common.saas.cache.SaaSAppDataSourceClusterRedisRepository;
import net.northking.cctp.common.saas.db.MultiClusterDynamicDataSource;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.core.RedisTemplate;

/**
 * SaaS模式相关配置
 *
 * @author xiusong.xie
 * @since 2.4
 */
@Configuration
public class SaaSConfiguration
{
  private static final Logger logger = LoggerFactory.getLogger(SaaSConfiguration.class);

  @Autowired
  private RedisTemplate<String, Object> redisTemplate;


  /**
   * SaaS应用数据源集群缓存
   *
   * @return SaaS应用数据源集群缓存
   */
  @Bean
  public SaaSAppDataSourceClusterCache tenantAppDataSourceClusterCache()
  {
    logger.info("注册公共组件提示： SaaS模式 => SaaS应用数据源集群缓存(SaaSAppDataSourceClusterCache) 已完成。");
    return new SaaSAppDataSourceClusterRedisRepository(redisTemplate);
  }

  @Bean(name = "datasource")
  public MultiClusterDynamicDataSource multiClusterDataSource(SaaSProperties properties)
  {
    MultiClusterDynamicDataSource dataSource = new MultiClusterDynamicDataSource();
    dataSource.setAppName(properties.getAppName());
    dataSource.setMultiClusterProperties(properties.getDataSourceClusterProperties());
    dataSource.setClusterCache(tenantAppDataSourceClusterCache());
    logger.info("注册公共组件提示： SaaS模式 => 多集群数据源MultiClusterDynamicDataSource 已启用。");

    return dataSource;
  }
}
