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

import com.airlock.iam.base.api.domain.model.exception.ViolationException;
import com.airlock.iam.common.infrastructure.logger.LogTypes;
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.core.Response;
import jakarta.ws.rs.core.Response.Status;
import jakarta.ws.rs.ext.ExceptionMapper;

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

   @Inject
   public Saml2ExceptionMapper(Provider<Saml2ErrorUri> errorUri) {
      this.errorUri = errorUri;
   }

   public Response toResponse(Exception exception) {
      if (exception instanceof ViolationException) {
         this.logWithoutStackTrace(exception);
      } else {
         this.logWithStackTrace(exception);
      }

      return Response.status(Status.FOUND).header("Location", ((Saml2ErrorUri)this.errorUri.get()).getUri()).build();
   }

   private void logWithoutStackTrace(Exception exception) {
      LOG.info(LogTypes.REST_EXCEPTION_HANDLER, "Exception occurred during SAML 2.0: " + exception.getMessage());
   }

   private void logWithStackTrace(Exception exception) {
      LOG.error(LogTypes.REST_EXCEPTION_HANDLER, "Exception occurred during SAML 2.0", exception);
   }
}
