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;
import java.util.List;

@Service
public class UserService {
    
    @Autowired
    private UserRepository userRepository;
    
    @Autowired
    private PasswordEncoder passwordEncoder;
    
    public User getCurrentUser() {
        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        String phoneNumber = authentication.getName();
        return userRepository.findByPhoneNumber(phoneNumber)
                .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 phoneNumber, String password, String displayName) {
        if (!isCurrentUserAdmin()) {
            throw new RuntimeException("Access denied: Admin privileges required");
        }
        
        if (userRepository.existsByPhoneNumber(phoneNumber)) {
            throw new RuntimeException("User with this phone number already exists");
        }
        
        User user = new User(phoneNumber, passwordEncoder.encode(password), displayName);
        return userRepository.save(user);
    }
    
    public User updateUser(String fcmToken, String displayName, String avatar, String password, String username, List<String> subscriptions) {
        User user = getCurrentUser();
        boolean wasNotActivated = !user.isActivated();
        
        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));
        }
        
        if (username != null && !username.trim().isEmpty()) {
            // Check if username is different from current username to avoid false positives
            if (!username.equals(user.getUsername()) && userRepository.existsByUsername(username)) {
                System.out.println("Username taken!");
                throw new RuntimeException("@" + username + " is already taken. Try another username");
            }
            System.out.println("It still happened here");
            user.setUsername(username);
        }
        
        if (subscriptions != null && !subscriptions.isEmpty()) {
            user.setSubscriptions(subscriptions);
        }
        
        User savedUser = userRepository.save(user);
        
        if (wasNotActivated) {
            savedUser.setActivated(true);
            savedUser = userRepository.save(savedUser);
        }
        
        return savedUser;
    }
}