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

import jakarta.servlet.http.HttpServletResponse;
import jakarta.servlet.http.HttpServletResponseWrapper;
import java.nio.charset.UnsupportedCharsetException;
import org.apache.hc.core5.http.ContentType;

public class Saml2Response extends HttpServletResponseWrapper {
   public Saml2Response(HttpServletResponse response) {
      super(response);
   }

   public boolean isHandledBySaml2Library() {
      return this.isCommitted() || this.containsHeader("Location") || contentTypeIsTextHtml(this.getContentType());
   }

   public void sendRedirect(String location) {
      this.setStatus(302);
      this.setHeader("Location", location);
      this.setContentType("text/plain; charset=utf-8");
   }

   static boolean contentTypeIsTextHtml(String responseContentType) {
      if (responseContentType == null) {
         return false;
      }

      try {
         ContentType contentType = ContentType.parse(responseContentType);
         return contentType.getMimeType().equalsIgnoreCase(ContentType.TEXT_HTML.getMimeType());
      } catch (UnsupportedCharsetException e) {
         return false;
      }
   }
}
