package sklep.security;

import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.config.annotation.ObjectPostProcessor;
import org.springframework.security.config.annotation.authentication.configuration.AuthenticationConfiguration;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.web.SecurityFilterChain;

@Configuration
@EnableWebSecurity
public class SecurityConfig {
	
	@Bean
	SecurityFilterChain setHttpSecurity(HttpSecurity httpSecurity) throws Exception {
		httpSecurity
			.authorizeHttpRequests((authz) -> authz
					//.anyRequest().permitAll()
//					.requestMatchers(antMatcher("/")).permitAll()
//					.requestMatchers("/whoami").permitAll()
//					.requestMatchers("/*.css").permitAll()
//					.requestMatchers("/hello", "/time").permitAll()
//					.requestMatchers("/alt?/**").authenticated() // zalogowany jako ktokolwiek
//					.requestMatchers("/products/new", "/products/*/edit").hasAuthority("ROLE_manager")
//					.requestMatchers("/products/**").permitAll()
//					.requestMatchers("/customers/new", "/customers/*/edit").hasAuthority("ROLE_manager")
//					.requestMatchers("/customers/**").authenticated()
					.anyRequest().authenticated()
//					.anyRequest().denyAll()
				)
			.formLogin();
		return httpSecurity.build();
	}

//	@Bean
//	public InMemoryUserDetailsManager userDetailsService() {
//		UserDetails user = User.withUsername("ala").password("{noop}kot").roles("manager")
//				.build();
//		return new InMemoryUserDetailsManager(user);
//	}
	
	@Bean
	AuthenticationManager authenticationManager(AuthenticationConfiguration authenticationConfiguration, ApplicationContext applicationContext) throws Exception {
        ObjectPostProcessor<Object> objectPostProcessor = new ObjectPostProcessor<Object>() {
			public <O> O postProcess(O object) {
				return object;
			}
		};
		
		return authenticationConfiguration.authenticationManagerBuilder(objectPostProcessor, applicationContext)
				.inMemoryAuthentication()
				.withUser("ala").password("{noop}abc123").roles("manager", "worker").and()
				.withUser("ola").password("{noop}abc123").roles("worker").and()
			.and()
			.build();
	}

}
