package com.spring.web.support;

import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ModelAttribute;

import com.spring.domain.user.entity.AgentUserRole;
import com.spring.infra.security.domain.UserPrincipal;
import com.spring.web.constant.Menus;

@ControllerAdvice(basePackages = "com.spring.web.controller")
public class GlobalControllerAdvice {
    
    @ModelAttribute("userInfo")
    public Map<String, String> userInfo() {
        Authentication auth = SecurityContextHolder.getContext().getAuthentication();
        if (auth != null && auth.isAuthenticated() && auth.getPrincipal() instanceof UserPrincipal) {
            UserPrincipal user = (UserPrincipal) auth.getPrincipal();
            return Map.of("userId", user.getUsername(), "userName", user.getMemberName());
        }
        return Map.of("userId", "", "userName", "");
    }

    @ModelAttribute("menus")
    public List<Map<String, String>> getMenus() {
        Authentication auth = SecurityContextHolder.getContext().getAuthentication();
        if (auth != null && auth.isAuthenticated()) {
            AgentUserRole userRole = auth.getAuthorities().stream()
                .map(role -> role.getAuthority())
                .map(AgentUserRole::fromRole)
                .findFirst()
                .orElse(AgentUserRole.ROLE_USER);

            return Menus.fromRole(userRole).stream()
                .map(menu -> Map.of("menuUri", menu.getMenuUri(), "menuName", menu.getMenuName(), "menuIcon", menu.getMenuIcon()))
                .collect(Collectors.toList());
        }
        return Collections.emptyList();
    }

}
