package dev.lions.unionflow.client.security;

import jakarta.annotation.Priority;
import jakarta.inject.Inject;
import jakarta.ws.rs.client.ClientRequestContext;
import jakarta.ws.rs.client.ClientRequestFilter;
import jakarta.ws.rs.core.HttpHeaders;
import jakarta.ws.rs.ext.Provider;
import java.io.IOException;
import java.util.logging.Logger;

@Provider
@Priority(1000)
public class JwtClientRequestFilter implements ClientRequestFilter {
    
    private static final Logger LOGGER = Logger.getLogger(JwtClientRequestFilter.class.getName());
    
    @Inject
    private JwtTokenManager tokenManager;
    
    @Override
    public void filter(ClientRequestContext requestContext) throws IOException {
        if (tokenManager == null) {
            LOGGER.fine("JwtTokenManager non disponible, requête sans authentification");
            return;
        }
        
        try {
            String authHeader = tokenManager.getAuthorizationHeader();
            
            if (authHeader != null && !isAuthEndpoint(requestContext.getUri().getPath())) {
                requestContext.getHeaders().add(HttpHeaders.AUTHORIZATION, authHeader);
                LOGGER.fine("JWT token ajouté à la requête: " + requestContext.getUri());
            }
        } catch (Exception e) {
            LOGGER.warning("Erreur lors de l'ajout du token JWT: " + e.getMessage());
            // Continuer sans authentification plutôt que de bloquer la requête
        }
    }
    
    private boolean isAuthEndpoint(String path) {
        return path != null && (
            path.contains("/auth/login") || 
            path.contains("/auth/register") ||
            path.contains("/auth/refresh") ||
            path.contains("/public/")
        );
    }
}