package fr.eni.enchere.interceptor;

import fr.eni.enchere.bll.EnchereService;
import fr.eni.enchere.bll.UserService;
import fr.eni.enchere.bo.Enchere;
import fr.eni.enchere.bo.UserProfil;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.beans.factory.annotation.Autowired;
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 org.springframework.web.servlet.ModelAndView;

import java.util.List;

@Component
public class UserInterceptor implements HandlerInterceptor {

    private final UserService userService;
    private final EnchereService enchereService;

    @Autowired
    public UserInterceptor(UserService userService, EnchereService enchereService) {
        this.userService = userService;
        this.enchereService = enchereService;
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
        if (modelAndView != null && modelAndView.getModelMap() != null) {
            Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
            if (authentication != null && authentication.isAuthenticated() && !authentication.getName().equals("anonymousUser")) {
                UserProfil user = this.userService.utilisateurByName(authentication.getName());
                List<Enchere> enchere = this.enchereService.enchereByUser(user.getId());
                double encheresSum = enchere.stream()
                        .mapToDouble(ench -> ench.getMontantEnchere()) // Mappez chaque enchère à son montant
                        .sum();
                if (modelAndView != null && modelAndView.getViewName() != null && !modelAndView.getViewName().startsWith("redirect:")) {
                    modelAndView.addObject("user", user);
                    modelAndView.addObject("enchereUser", encheresSum);
                }
            }
        }
    }
}
