package com.astalange.web.config;

import com.astalange.core.security.CustomUserDetails;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

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

@Component
public class PasswordChangeInterceptor implements HandlerInterceptor {

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        Authentication auth = SecurityContextHolder.getContext().getAuthentication();
        if (auth != null && auth.isAuthenticated() && auth.getPrincipal() instanceof CustomUserDetails) {
            CustomUserDetails userDetails = (CustomUserDetails) auth.getPrincipal();
            if (userDetails.isMustChangePassword()) {
                String uri = request.getRequestURI();
                // Exclude /change-password, /logout, static assets, error pages
                if (!uri.equals("/change-password") && 
                    !uri.equals("/logout") && 
                    !uri.startsWith("/css/") && 
                    !uri.startsWith("/js/") && 
                    !uri.startsWith("/images/") &&
                    !uri.equals("/error")) {
                    response.sendRedirect("/change-password");
                    return false;
                }
            }
        }
        return true;
    }
}
