package com.eactive.testmaster.config;

import com.fasterxml.jackson.databind.ObjectMapper;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import org.springframework.http.MediaType;
import org.springframework.security.core.Authentication;
import org.springframework.security.web.authentication.AuthenticationSuccessHandler;
import org.springframework.stereotype.Component;

@Component
public class AjaxAuthenticationSuccessHandler implements AuthenticationSuccessHandler {

    private final PortalAuthenticationSuccessHandler delegate;
    private final ObjectMapper objectMapper;

    public AjaxAuthenticationSuccessHandler(PortalAuthenticationSuccessHandler delegate, ObjectMapper objectMapper) {
        this.delegate = delegate;
        this.objectMapper = objectMapper;
    }

    @Override
    public void onAuthenticationSuccess(HttpServletRequest request, HttpServletResponse response,
        Authentication authentication) throws IOException, ServletException {
        if ("XMLHttpRequest".equals(request.getHeader("X-Requested-With"))) {
            Map<String, Object> result = new HashMap<>();
            HttpSession session = request.getSession();

            // Check for special conditions (reusing logic from original handler)
            if (session.getAttribute("dormantAccount") != null) {
                result.put("status", "DORMANT");
                result.put("message", session.getAttribute("success"));
                result.put("redirectUrl", session.getAttribute("redirectUrl"));
            } else if (session.getAttribute("passwordExpired") != null) {
                result.put("status", "PASSWORD_EXPIRED");
                result.put("message", session.getAttribute("success"));
                result.put("redirectUrl", session.getAttribute("redirectUrl"));
            } else {
                result.put("status", "SUCCESS");
                result.put("redirectUrl", request.getContextPath() + "/");
            }

            response.setContentType(MediaType.APPLICATION_JSON_VALUE);
            objectMapper.writeValue(response.getWriter(), result);
        } else {
            delegate.onAuthenticationSuccess(request, response, authentication);
        }
    }
}
