package com.airlock.iam.common.infrastructure.factory.uriinfo;

import com.airlock.iam.elog.api.EDefaultLogType;
import com.airlock.iam.elog.api.ELogger;
import com.airlock.iam.elog.api.ELoggerFactory;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.ws.rs.core.UriBuilder;
import jakarta.ws.rs.core.UriInfo;
import java.net.URI;
import java.nio.file.Paths;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.lang3.Strings;

final class ExternalUriInfoFromGateway extends ExternalUriInfoBase {
   private static final ELogger LOG = ELoggerFactory.getLogger(ExternalUriInfoFromGateway.class);
   private final URI gatewayBaseUri;
   private final URI gatewayRequestUri;
   private final HttpServletRequest request;

   ExternalUriInfoFromGateway(URI requestUri, UriInfo uriInfo, HttpServletRequest request) {
      super(uriInfo);
      this.gatewayRequestUri = requestUri;
      this.request = request;
      String path = uriInfo.getPath(false);
      if (this.gatewayRequestUri.toString().endsWith("/")) {
         path = Strings.CS.appendIfMissing(path, "/", new CharSequence[0]);
      } else {
         path = StringUtils.stripEnd(path, "/");
      }

      if (Paths.get(this.gatewayRequestUri.getRawPath()).endsWith(path)) {
         this.gatewayBaseUri = URI.create(Strings.CS.removeEnd(this.gatewayRequestUri.toString(), path));
      } else {
         this.gatewayBaseUri = this.gatewayRequestUri;
      }
   }

   @Override
   public URI getBaseUri() {
      if (this.request.getAttribute("jakarta.servlet.forward.request_uri") != null) {
         LOG.warn(EDefaultLogType.GENERIC_LOG_TYPE, "ExternalUriInfo does not support servlet forwards. Returned URIs might not be correct.");
      }

      return UriBuilder.fromUri(this.gatewayBaseUri).build(new Object[0]);
   }

   @Override
   public URI getRequestUri() {
      return this.buildRequestUri(this.gatewayRequestUri);
   }
}
