package com.saas.shared.security;

import com.saas.admin.entity.User;
import com.saas.admin.repository.UserRepository;
import com.saas.admin.repository.UserRoleRepository;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
@RequiredArgsConstructor
@Slf4j
public class CustomUserDetailsService implements UserDetailsService {
    
    private final UserRepository userRepository;
    private final UserRoleRepository userRoleRepository;
    
    @Override
    public UserDetails loadUserByUsername(String email) throws UsernameNotFoundException {
        User user = userRepository.findByEmail(email)
                .orElseThrow(() -> new UsernameNotFoundException("User not found with email: " + email));
        
        // Load RBAC permissions aggregated from all user roles
        List<String> permissions = userRoleRepository.findAllPermissionsByUserId(user.getId());
        
        log.debug("🔐 Loading user: {} with {} permissions", email, permissions.size());
        
        return new UserPrincipal(
                user.getId(),
                user.getEmail(),
                user.getPassword(),
                user.getRole(),
                user.getUserType(),
                permissions
        );
    }
    
    public UserDetails loadUserById(Long id) {
        User user = userRepository.findById(id)
                .orElseThrow(() -> new UsernameNotFoundException("User not found with id: " + id));
        
        // Load RBAC permissions aggregated from all user roles
        List<String> permissions = userRoleRepository.findAllPermissionsByUserId(id);
        
        log.debug("🔐 Loading user ID: {} with {} permissions", id, permissions.size());
        
        return new UserPrincipal(
                user.getId(),
                user.getEmail(),
                user.getPassword(),
                user.getRole(),
                user.getUserType(),
                permissions
        );
    }
}
