package com.airlock.iam.common.infrastructure.exception;

import com.airlock.iam.base.api.infrastructure.uri.ExternalUriInfo;
import com.airlock.iam.base.infrastructure.error.ErrorResponse;
import com.airlock.iam.base.misc.log.LogUtil;
import com.airlock.iam.common.infrastructure.logger.LogTypes;
import com.airlock.iam.elog.api.ELogger;
import com.airlock.iam.elog.api.ELoggerFactory;
import jakarta.inject.Inject;
import jakarta.inject.Provider;
import jakarta.ws.rs.core.Response;
import jakarta.ws.rs.core.Response.Status;
import jakarta.ws.rs.ext.ExceptionMapper;
import org.apache.commons.lang3.Strings;
import org.glassfish.jersey.server.ParamException.PathParamException;

@jakarta.ws.rs.ext.Provider
public final class PathParamExceptionMapper implements ExceptionMapper<PathParamException> {
   private static final ELogger LOG = ELoggerFactory.getLogger(PathParamExceptionMapper.class);
   private final Provider<ExternalUriInfo> uriInfo;

   @Inject
   public PathParamExceptionMapper(Provider<ExternalUriInfo> uriInfo) {
      this.uriInfo = uriInfo;
   }

   public Response toResponse(PathParamException exception) {
      String requestPath = LogUtil.logSafeQuote(Strings.CS.prependIfMissing(((ExternalUriInfo)this.uriInfo.get()).getPath(), "/", new CharSequence[0]));
      LOG.info(
         LogTypes.REST_EXCEPTION_HANDLER, "Answered call to " + requestPath + " with " + exception.getMessage() + ". Error during evaluation of PathParam."
      );
      return ErrorResponse.builder().status(Status.fromStatusCode(exception.getResponse().getStatus())).build().toResponse();
   }
}
