package ru.ibs.socrates.confexporter.config;

import feign.Logger;
import java.util.Arrays;
import lombok.extern.slf4j.Slf4j;
import org.springframework.cloud.openfeign.EnableFeignClients;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;


@Slf4j
@EnableFeignClients(basePackages = "ru.ibs.socrates.confexporter.external")
@Configuration
public class FeignConfig {

  @Bean(name = "feignLogger")
  Logger logger() {
    return new CustomFeignRequestLogging();
  }


  public static class CustomFeignRequestLogging extends feign.Logger {

    private static final int MAX_LOG_LENGTH = 512;

    @Override
    protected void log(String configKey, String format, Object... args) {
      if (log.isDebugEnabled()) {
        log.debug(String.format(methodTag(configKey) + format, truncateLogs(args)));
      } else if (log.isInfoEnabled()) {
        log.info(String.format(methodTag(configKey) + format, truncateLogs(args)));
      }
    }

    private static Object[] truncateLogs(Object[] args) {
      return Arrays.stream(args)
          .map(arg -> {
            if (arg instanceof String s && s.length() > MAX_LOG_LENGTH) {
              return s.substring(0, MAX_LOG_LENGTH) + "...";
            }
            return arg;
          })
          .toArray();
    }
  }
}
