package fr.eni.enchere.security;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.security.web.SecurityFilterChain;
import org.springframework.security.web.util.matcher.AntPathRequestMatcher;

@Configuration
@EnableWebSecurity
public class WebSecurityConfig{

    @Bean
    public SecurityFilterChain securityFilterChain(HttpSecurity http) throws Exception {
        http.authorizeHttpRequests((requests) -> requests
                        .requestMatchers("/", "/accueil").permitAll()
                        .requestMatchers("/accueil", "/login", "/inscription/**", "/searchArticle", "/article/**", "/change-language").permitAll()
                        .requestMatchers("/css/**", "/images/**", "/assets/**", "/img/**", "/js/**").permitAll()
                        .requestMatchers("/profil/**", "/article/new/**", "/article/update", "/article/delete").authenticated()
                        .requestMatchers("/admin").hasRole("ADMIN")
                        .anyRequest().authenticated())
                .formLogin((form) -> form.loginPage("/login").defaultSuccessUrl("/", true))
                .logout((logout) -> logout.clearAuthentication(true).invalidateHttpSession(true)
                        .deleteCookies("JSESSIONID").logoutSuccessUrl("/logout")
                        .logoutRequestMatcher(new AntPathRequestMatcher("/logout")).permitAll());

        return http.build();
    }

    @Bean
    public PasswordEncoder passwordEncoder() {
        return new BCryptPasswordEncoder();

    }

}
