package com.airlock.iam.common.domain.model.request;

import com.airlock.iam.elog.api.ELogger;
import com.airlock.iam.elog.api.ELoggerFactory;
import edu.umd.cs.findbugs.annotations.SuppressFBWarnings;
import jakarta.annotation.Nonnull;
import lombok.NonNull;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.lang3.Validate;

public final class UserAgentRequestHeader {
   private static final ELogger LOG = ELoggerFactory.getLogger(UserAgentRequestHeader.class);
   static final int MAXIMAL_LENGTH = 4000;
   @NonNull
   private final String value;

   private UserAgentRequestHeader(@NonNull String value) {
      if (value == null) {
         throw new NullPointerException("value is marked non-null but is null");
      }

      Validate.notBlank(value);
      Validate.matchesPattern(value, "\\p{ASCII}+", "User-Agent request header contains non US-ASCII characters!", new Object[0]);
      this.value = truncateIfNecessary(value);
   }

   @Nonnull
   private static String truncateIfNecessary(@Nonnull String value) {
      if (value.length() > 4000) {
         LOG.info(
            String.format(
               "User-Agent request header contains %d characters and is too long. Only the first %d characters will be considered.", value.length(), 4000
            )
         );
      }

      return StringUtils.truncate(value, 4000);
   }

   public static UserAgentRequestHeader userAgent(String value) {
      return new UserAgentRequestHeader(value);
   }

   @Override
   public String toString() {
      return String.format("User-Agent: %s", this.value);
   }

   @NonNull
   @SuppressFBWarnings(justification = "generated code")
   public String value() {
      return this.value;
   }

   @SuppressFBWarnings(justification = "generated code")
   @Override
   public boolean equals(Object o) {
      if (o == this) {
         return true;
      } else if (!(o instanceof UserAgentRequestHeader other)) {
         return false;
      } else {
         Object this$value = this.value;
         Object other$value = other.value;
         return this$value == null ? other$value == null : this$value.equals(other$value);
      }
   }

   @SuppressFBWarnings(justification = "generated code")
   @Override
   public int hashCode() {
      int PRIME = 59;
      int result = 1;
      Object $value = this.value;
      return result * 59 + ($value == null ? 43 : $value.hashCode());
   }
}
