package online.wesal.wesal.service;

import online.wesal.wesal.entity.User;
import online.wesal.wesal.repository.UserRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;

@Service
public class UserService {
    
    @Autowired
    private UserRepository userRepository;
    
    @Autowired
    private PasswordEncoder passwordEncoder;
    
    public User getCurrentUser() {
        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        String email = authentication.getName();
        return userRepository.findByEmail(email)
                .orElseThrow(() -> new RuntimeException("User not found"));
    }
    
    public User setUsername(String username) {
        if (userRepository.existsByUsername(username)) {
            throw new RuntimeException("Username already taken");
        }
        
        User user = getCurrentUser();
        if (user.getUsername() != null) {
            throw new RuntimeException("Username already set and cannot be changed");
        }
        
        user.setUsername(username);
        return userRepository.save(user);
    }
    
    public boolean isCurrentUserAdmin() {
        User user = getCurrentUser();
        return "ADMIN".equals(user.getRole());
    }
    
    public User createUser(String email, String password, String displayName) {
        if (!isCurrentUserAdmin()) {
            throw new RuntimeException("Access denied: Admin privileges required");
        }
        
        if (userRepository.existsByEmail(email)) {
            throw new RuntimeException("User with this email already exists");
        }
        
        User user = new User(email, passwordEncoder.encode(password), displayName);
        return userRepository.save(user);
    }
    
    public User updateUser(String fcmToken, String displayName, String avatar, String password) {
        User user = getCurrentUser();
        
        if (fcmToken != null && !fcmToken.trim().isEmpty()) {
            user.setFcmToken(fcmToken);
        }
        
        if (displayName != null && !displayName.trim().isEmpty()) {
            user.setDisplayName(displayName);
        }
        
        if (avatar != null) {
            user.setAvatar(avatar);
        }
        
        if (password != null && !password.trim().isEmpty()) {
            user.setPassword(passwordEncoder.encode(password));
        }
        
        return userRepository.save(user);
    }
}