package com.example.chiptuningweb.security;


import com.example.chiptuningweb.service.CustomUserDetailsService;
import org.springframework.beans.factory.annotation.Autowired;
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.password.NoOpPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.security.web.SecurityFilterChain;

@Configuration
@EnableWebSecurity
public class SecurityConfig {

    @Autowired
    private CustomUserDetailsService userDetailsService;

    @Bean
    public SecurityFilterChain securityFilterChain(HttpSecurity http) throws Exception {
        http
                .authorizeHttpRequests(auth -> auth
                        .requestMatchers("/admin/token/sogjfLJFJfvjLSfjo93045ujgfdfLAdjej4/full").hasAuthority("ROLE_ADMIN")

                        //.requestMatchers( "/check/**").authenticated()

                        .requestMatchers("/", "/formdann", "/vixlop", "/kraska", "/sity/**",
                                "/admin/token/dfhvidhEUefhier254kHDerf/regisation",
                                "/css/**", "/js/**", "/images/**").permitAll()
                        .anyRequest().authenticated()
                )
                .formLogin(form -> form
                        .loginPage("/") // /admin/token/sogjfLJFJfvjLSfjo93045ujgfdfLAdjej4/autoisation
                        .loginProcessingUrl("/admin/token/sogjfLJFJfvjLSfjo93045ujgfdfLAdjej4/autoisation")
                        .defaultSuccessUrl("/admin/token/sogjfLJFJfvjLSfjo93045ujgfdfLAdjej4/full")
                        .failureUrl("/admin/token/sogjfLJFJfvjLSfjo93045ujgfdfLAdjej4/autoisation?error=true")
                        .permitAll()
                )
                .logout(logout -> logout
                        .logoutSuccessUrl("/admin/token/sogjfLJFJfvjLSfjo93045ujgfdfLAdjej4/autoisation")
                        .permitAll()
                )
                .csrf(csrf -> csrf.disable()) // Отключаем CSRF для упрощения
                .userDetailsService(userDetailsService); // Используем кастомный UserDetailsService

        return http.build();
    }

    @Bean
    public PasswordEncoder passwordEncoder() {
        return NoOpPasswordEncoder.getInstance();
    }
}