package es.uv.garcosda.auth.services;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;
import org.springframework.web.reactive.function.client.WebClient;

import es.uv.garcosda.shared.domain.User;
import reactor.core.publisher.Mono;

@Service
public class UserService {
	
	@Autowired
	WebClient.Builder client;
	
	@Value("${mailer.data.url}")
	private String data_api;

	
	public User findByEmail(String email) {
		Mono<User> u = client.build().get()
				 .uri(data_api+"/users/email/"+email)
				 .retrieve()
				 .bodyToMono(User.class)
				 .switchIfEmpty(Mono.defer(() ->	
					Mono.error(new UsernameNotFoundException("User Not Found"))));
		
		return u.block();
	}
	
	public Mono<User> findByEmailMono(String email) {
		Mono<User> u = client.build().get()
				 .uri(data_api+"/users/email/"+email)
				 .retrieve()
				 .bodyToMono(User.class)
				 .switchIfEmpty(Mono.defer(() ->	
					Mono.error(new UsernameNotFoundException("User Not Found"))));
		
		return u;
	}

	
}
