package com.mvrent.carrental.config;

import com.mvrent.carrental.repository.UserRepository;
import lombok.RequiredArgsConstructor;
import org.springframework.security.authentication.AnonymousAuthenticationToken;
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 java.util.HashMap;
import java.util.Map;

/**
 * Exposes the logged-in user's display details to every view as {@code cu}
 * (used by the topbar avatar / profile dropdown).
 */
@ControllerAdvice
@RequiredArgsConstructor
public class CurrentUserAdvice {

    private final UserRepository userRepository;

    @ModelAttribute("cu")
    public Map<String, String> currentUser() {
        Authentication auth = SecurityContextHolder.getContext().getAuthentication();
        if (auth == null || !auth.isAuthenticated() || auth instanceof AnonymousAuthenticationToken) {
            return null;
        }
        return userRepository.findByUsername(auth.getName()).map(u -> {
            Map<String, String> m = new HashMap<>();
            String fullName = (u.getFullName() != null && !u.getFullName().isBlank())
                    ? u.getFullName() : u.getUsername();
            m.put("username", u.getUsername());
            m.put("fullName", fullName);
            m.put("email", u.getEmail());
            m.put("role", u.getRole().name());
            m.put("initials", initials(fullName));
            return m;
        }).orElse(null);
    }

    private static String initials(String name) {
        String[] parts = name.trim().split("\\s+");
        if (parts.length >= 2 && !parts[0].isEmpty() && !parts[1].isEmpty()) {
            return ("" + parts[0].charAt(0) + parts[1].charAt(0)).toUpperCase();
        }
        return name.substring(0, Math.min(2, name.length())).toUpperCase();
    }
}
