package com.mx.dla.configuration;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.security.core.Authentication;
import org.springframework.security.web.authentication.logout.LogoutSuccessHandler;
import org.springframework.stereotype.Component;

import com.mx.dla.admin.daos.UsuarioDAO;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.time.LocalDateTime;

@Component
public class CustomLogoutSuccessHandler implements LogoutSuccessHandler {
	
	@Autowired
	private UsuarioDAO usuarioDAO;
	
	@Value("${login.uri}")
	private String uri;
	
	protected Logger logger = LoggerFactory.getLogger("app");

    @Override
    public void onLogoutSuccess(HttpServletRequest request, HttpServletResponse response,
                                Authentication authentication) throws IOException, ServletException {
        // Log en la consola
    	String ipAddress = request.getHeader("X-FORWARDED-FOR");
        if (ipAddress == null || ipAddress.isEmpty()) {
            ipAddress = request.getRemoteAddr();
        }
        ipAddress = ipAddress.split(",")[0];
        String userAgent = request.getHeader("User-Agent");
        
        
        if (authentication != null) {
        	logger.info("Logout successful: " + authentication.getName() + " at " + LocalDateTime.now());
            usuarioDAO.actualizaEstadoSesion(1, authentication.getName());
            usuarioDAO.insertaBitacora("LogOut Exitoso", authentication.getName(), ipAddress, userAgent);
        }

        // Redirigir al usuario a la página de login
        response.sendRedirect("/" + uri + "/index.jsp");
    }
}

