package com.example.service;

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 org.springframework.transaction.annotation.Transactional;

import com.example.domain.LoginUser;
import com.example.repository.UserRepository;

import lombok.extern.slf4j.Slf4j;

@Service
@Slf4j
public class LoginUserDetailsService implements UserDetailsService {
	private final UserRepository userRepository;
	
	public LoginUserDetailsService(UserRepository userRepository){
		this.userRepository = userRepository;
	}
	
	@Transactional(readOnly = true)
	@Override
	public UserDetails loadUserByUsername(String email) throws UsernameNotFoundException{
		assert(email != null);
		log.debug("loadUserByUsername(email):[{}]", email);
		return userRepository.findByEmail(email)
				.map(LoginUser::new)
				.orElseThrow(() -> new UsernameNotFoundException("User not found by email:[" + email + "]"));
	}
}
