package com.project.whatsappchatbot.security.services;

import com.project.whatsappchatbot.model.Account;
import com.project.whatsappchatbot.repository.AccountRepository;
import org.springframework.beans.factory.annotation.Autowired;
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 java.util.Optional;

@Service
public class UserDetailsServiceImpl implements UserDetailsService {
	@Autowired
    AccountRepository accountRepository;

	@Override
	@Transactional
	public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
		Optional<Account> optionalAccount = Optional.ofNullable(accountRepository.findByUsername(username));
		Account account = optionalAccount.orElseThrow(() -> new UsernameNotFoundException("User Not Found with username: " + username));

		return new UserDetailsImpl(account);
	}
}

