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

import com.airlock.iam.base.api.infrastructure.uri.ExternalUriInfo;
import com.airlock.iam.base.misc.log.LogUtil;
import com.airlock.iam.elog.api.EDefaultLogType;
import com.airlock.iam.elog.api.ELogger;
import com.airlock.iam.elog.api.ELoggerFactory;
import com.airlock.iam.saml2.domain.model.Saml2ErrorUri;
import jakarta.inject.Inject;
import jakarta.inject.Provider;
import jakarta.ws.rs.NotFoundException;
import jakarta.ws.rs.core.Response;
import jakarta.ws.rs.core.Response.Status;
import jakarta.ws.rs.ext.ExceptionMapper;

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

   @Inject
   public NotFoundExceptionMapper(Provider<Saml2ErrorUri> errorUri, Provider<ExternalUriInfo> uriInfo) {
      this.errorUri = errorUri;
      this.uriInfo = uriInfo;
   }

   public Response toResponse(NotFoundException exception) {
      LOG.warn(
         EDefaultLogType.GENERIC_LOG_TYPE,
         "Redirecting to error page since requested URI was not found: " + LogUtil.logSafeQuote(((ExternalUriInfo)this.uriInfo.get()).getAbsolutePath())
      );
      return Response.status(Status.FOUND).header("Location", ((Saml2ErrorUri)this.errorUri.get()).getUri()).build();
   }
}
