package com.kamco.cd.training.common.utils;

import jakarta.servlet.http.HttpServletRequest;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.context.request.RequestAttributes;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

@Slf4j
public final class HeaderUtil {

  private HeaderUtil() {}

  /** 특정 Header 값 조회 */
  public static String get(HttpServletRequest request, String headerName) {
    if (request == null || headerName == null) {
      return null;
    }

    String value = request.getHeader(headerName);
    return (value != null && !value.isBlank()) ? value : null;
  }

  /** 필수 Header 조회 (없으면 null) */
  public static String getRequired(HttpServletRequest request, String headerName) {
    return get(request, headerName);
  }

  public static boolean isEnglishRequest() {
    RequestAttributes attrs = RequestContextHolder.getRequestAttributes();

    if (!(attrs instanceof ServletRequestAttributes servletAttrs)) {
      return false;
    }

    String acceptLanguage = servletAttrs.getRequest().getHeader("Accept-Language");

    if (acceptLanguage == null || acceptLanguage.isBlank()) {
      return false;
    }

    return acceptLanguage.toLowerCase().startsWith("en");
  }
}
