package com.oguerreiro.resilient.security.saml2;

import java.io.IOException;
import java.util.Base64;

import org.springframework.web.filter.OncePerRequestFilter;

import jakarta.servlet.FilterChain;
import jakarta.servlet.ServletException;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;

public class Saml2ResponseLoggingFilter extends OncePerRequestFilter {

  @Override
  protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain)
      throws ServletException, IOException {

    if ("POST".equalsIgnoreCase(request.getMethod()) && request.getRequestURI().contains("/sso")) {
      String samlResponse = request.getParameter("SAMLResponse");
      if (samlResponse != null) {
        try {
          byte[] decodedBytes = Base64.getDecoder().decode(samlResponse);
          String decodedXml = new String(decodedBytes, java.nio.charset.StandardCharsets.UTF_8);
          if (logger.isInfoEnabled()) {
            // The logger.info() doesn't write linebreaks, it replaces "\n" for "_". VERY strange output in console and messes the XML. 
            // Decided to remove the linebreaks and output a clean XML, then I can copy and format the XML in Notepad++
            String cleanedXml = decodedXml.replaceAll("\\r?\\n", "");

            logger.info("========== SAMLResponse XML ==========");
            logger.info(cleanedXml);
            logger.info("======================================");
          }
        } catch (IllegalArgumentException e) {
          logger.warn("Failed to decode SAMLResponse", e);
        }
      }
    } else if ("/saml2/authenticate/mock-idp".equals(request.getRequestURI())) {
      System.out.println("saml2");
    }

    filterChain.doFilter(request, response);
  }

  public static String decodeSamlResponse(String samlResponse) {
    if (samlResponse != null) {
      try {
        byte[] decodedBytes = Base64.getDecoder().decode(samlResponse);
        String decodedXml = new String(decodedBytes, java.nio.charset.StandardCharsets.UTF_8);
        return decodedXml;
      } catch (IllegalArgumentException e) {
      }
    }

    return null;
  }
}
