package com.bonus.core.tenant;

import com.bonus.core.common.utils.TenantContextHolder;
import feign.RequestInterceptor;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.boot.autoconfigure.AutoConfiguration;
import org.springframework.context.annotation.Bean;

@AutoConfiguration
public class FeignTenantConfiguration {
   private static final Logger log = LoggerFactory.getLogger(FeignTenantConfiguration.class);
   private final TenantConfigProperties tenantConfigProperties;

   @Bean
   public RequestInterceptor feignTenantIdFiller() {
      return (template) -> {
         if (TenantContextHolder.getTenantId() == null) {
            log.warn("Feign tenant fill: there's no tenantId in threadLocal, fallback to null!");
         } else {
            template.header(this.tenantConfigProperties.getCarrierName(), new String[]{TenantContextHolder.getTenantId().toString()});
         }
      };
   }

   public FeignTenantConfiguration(final TenantConfigProperties tenantConfigProperties) {
      this.tenantConfigProperties = tenantConfigProperties;
   }
}
