package org.xyzh.auth.config;

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.config.http.SessionCreationPolicy;
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.authentication.UsernamePasswordAuthenticationFilter;
import org.xyzh.auth.filter.JwtAuthenticationFilter;

/**
 * @description    SecurityConfig.java文件描述 Spring Security配置
 * @filename    SecurityConfig.java
 * @author    yslg
 * @copyright xyzh
 * @since 2025-09-28
 */
@Configuration
@EnableWebSecurity
public class SecurityConfig {

    @Autowired
    private AuthProperties authProperties;

    @Autowired
    private JwtAuthenticationFilter jwtAuthenticationFilter;

    /**
     * @description    密码编码器
     * @return    PasswordEncoder 密码编码器
     * @author    yslg
     * @since 2025-09-28
     */
    @Bean
    public PasswordEncoder passwordEncoder() {
        return new BCryptPasswordEncoder();
    }

    /**
     * @description    安全过滤器链配置
     * @param    http HTTP安全配置
     * @return    SecurityFilterChain 安全过滤器链
     * @author    yslg
     * @since 2025-09-28
     */
    @Bean
    public SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
        // 白名单路径转换为数组
        String[] whiteListArray = authProperties.getWhiteList().toArray(new String[0]);

        http
            // 禁用CSRF
            .csrf(csrf -> csrf.disable())
            // 无状态session
            .sessionManagement(session -> session.sessionCreationPolicy(SessionCreationPolicy.STATELESS))
            // 配置授权规则
            .authorizeHttpRequests(authz -> authz
                .requestMatchers(whiteListArray).permitAll()
                .requestMatchers("/auth/login", "/auth/logout", "/auth/captcha").permitAll()
                .requestMatchers("/actuator/**").permitAll()
                .requestMatchers("/swagger-ui/**", "/v3/api-docs/**").permitAll()
                .requestMatchers("/favicon.ico", "/error").permitAll()
                .anyRequest().authenticated()
            )
            // 添加JWT过滤器
            .addFilterBefore(jwtAuthenticationFilter, UsernamePasswordAuthenticationFilter.class);

        return http.build();
    }
}
