package dev.lions.unionflow.client.security;

import dev.lions.unionflow.client.view.UserSession;
import jakarta.inject.Inject;
import jakarta.servlet.*;
import jakarta.servlet.annotation.WebFilter;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.logging.Logger;

@WebFilter(urlPatterns = {"/pages/secure/*", "/pages/admin/*", "/pages/super-admin/*", "/pages/membre/*"})
public class AuthenticationFilter implements Filter {
    
    private static final Logger LOGGER = Logger.getLogger(AuthenticationFilter.class.getName());
    
    @Inject
    private UserSession userSession;
    
    @Inject
    private JwtTokenManager tokenManager;
    
    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) 
            throws IOException, ServletException {
        
        HttpServletRequest httpRequest = (HttpServletRequest) request;
        HttpServletResponse httpResponse = (HttpServletResponse) response;
        
        String requestURI = httpRequest.getRequestURI();
        
        // Vérifier si l'utilisateur est authentifié
        if (!isAuthenticated()) {
            LOGGER.warning("Accès non autorisé à: " + requestURI);
            httpResponse.sendRedirect(httpRequest.getContextPath() + "/pages/public/login.xhtml");
            return;
        }
        
        // Vérifier les autorisations spécifiques
        if (!hasRequiredPermissions(requestURI)) {
            LOGGER.warning("Permissions insuffisantes pour: " + requestURI + 
                          " (Utilisateur: " + userSession.getUsername() + 
                          ", Type: " + userSession.getTypeCompte() + ")");
            httpResponse.sendRedirect(httpRequest.getContextPath() + "/pages/secure/access-denied.xhtml");
            return;
        }
        
        // Continuer la chaîne de filtres
        chain.doFilter(request, response);
    }
    
    private boolean isAuthenticated() {
        return userSession != null && 
               userSession.isAuthenticated() && 
               tokenManager != null && 
               tokenManager.hasValidTokens();
    }
    
    private boolean hasRequiredPermissions(String requestURI) {
        if (requestURI.contains("/pages/super-admin/")) {
            return userSession.isSuperAdmin();
        }
        
        if (requestURI.contains("/pages/admin/")) {
            return userSession.isAdmin();
        }
        
        if (requestURI.contains("/pages/membre/")) {
            return userSession.isMembre();
        }
        
        // Pages sécurisées générales - tout utilisateur authentifié
        if (requestURI.contains("/pages/secure/")) {
            return true;
        }
        
        return false;
    }
    
    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
        LOGGER.info("Filtre d'authentification initialisé");
    }
    
    @Override
    public void destroy() {
        LOGGER.info("Filtre d'authentification détruit");
    }
}