package ru.ldeloff.hedgehogcloud.service;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;
import ru.ldeloff.hedgehogcloud.entity.UserEntity;
import ru.ldeloff.hedgehogcloud.repository.RoleRepository;
import ru.ldeloff.hedgehogcloud.repository.UserRepository;

@Service
public class UserServiceImpl implements UserService {
    UserRepository userRepository;
    RoleRepository roleRepository;

    @Autowired
    public UserServiceImpl(UserRepository userRepository,
                           RoleRepository roleRepository) {
        this.userRepository = userRepository;
        this.roleRepository = roleRepository;
    }

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        UserEntity user = userRepository.findByUsername(username);
        if (user == null) {
            throw new UsernameNotFoundException("User not found");
        }
        return user;
    }

    @Override
    public void saveUser(UserEntity user) {
        UserEntity userTemp = getByUserName(user.getUsername());
        if (userTemp == null) {
            userRepository.save(user);
        }
    }

    @Override
    public UserEntity getByUserName(String name) {
        return userRepository.findByUsername(name);
    }


}
