package es.uv.garcosda.config;

import java.util.Arrays;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.method.configuration.EnableReactiveMethodSecurity;
import org.springframework.security.config.annotation.web.reactive.EnableWebFluxSecurity;
import org.springframework.security.config.web.server.ServerHttpSecurity;
import org.springframework.security.core.userdetails.MapReactiveUserDetailsService;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.security.web.server.SecurityWebFilterChain;

@EnableReactiveMethodSecurity
@EnableWebFluxSecurity
@Configuration
public class WebConfigSecurity {

	@Bean
    public PasswordEncoder passwordEncoder() {
        return new BCryptPasswordEncoder();
    }
	
	@Bean
	public MapReactiveUserDetailsService userDetailsService() {
		return new MapReactiveUserDetailsService(Arrays.asList(
        		User.withUsername("user")
					.password(passwordEncoder().encode("1234"))
					.roles("USER")
					.build(),
				User.withUsername("admin")
					.password(passwordEncoder().encode("1234"))
					.roles("USER")
					.build()));
	}
		
	@Bean
	public SecurityWebFilterChain securityFilterChain(ServerHttpSecurity http) {
		return http.csrf().disable()
				   .formLogin().disable()
				   .logout().disable()
				   .authorizeExchange(exchanges -> exchanges
				       .anyExchange().authenticated()
				   )
				   .httpBasic()
				   .and()
				   .build();
	}
	
}
