package com.lesingle.security.config;

import com.lesingle.security.filter.JwtAuthenticationFilter;
import com.lesingle.security.handler.AuthEntryPoint;
import com.lesingle.security.handler.CustomAccessDeniedHandler;
import lombok.RequiredArgsConstructor;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.HttpMethod;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.config.annotation.authentication.configuration.AuthenticationConfiguration;
import org.springframework.security.config.annotation.method.configuration.EnableMethodSecurity;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configurers.AbstractHttpConfigurer;
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.config.Customizer;
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;

/**
 * Spring Security 配置
 * 注意：context-path 是 /api，所以 /api/auth/login 在 Security 配置里只需写 /auth/login
 */
@Configuration
@EnableWebSecurity
@EnableMethodSecurity
@RequiredArgsConstructor
public class SecurityConfig {

    private final JwtAuthenticationFilter jwtAuthenticationFilter;
    private final AuthEntryPoint authEntryPoint;
    private final CustomAccessDeniedHandler accessDeniedHandler;

    @Bean
    public SecurityFilterChain securityFilterChain(HttpSecurity http) throws Exception {
        http
                // 禁用 CSRF（无状态 JWT 不需要）
                .csrf(AbstractHttpConfigurer::disable)
                // 启用 CORS（使用 CorsFilter Bean 的配置）
                .cors(Customizer.withDefaults())
                // 无状态会话
                .sessionManagement(session -> session.sessionCreationPolicy(SessionCreationPolicy.STATELESS))
                // 异常处理
                .exceptionHandling(exception -> exception
                        .authenticationEntryPoint(authEntryPoint)
                        .accessDeniedHandler(accessDeniedHandler))
                // 请求授权
                .authorizeHttpRequests(auth -> auth
                        // 公开接口 - 无需认证
                        .requestMatchers("/auth/login").permitAll()
                        .requestMatchers("/public/auth/**").permitAll()
                        // 终端设备认证接口
                        .requestMatchers("/device/auth/**").permitAll()
                        .requestMatchers(HttpMethod.GET, "/public/activities", "/public/activities/**").permitAll()
                        .requestMatchers(HttpMethod.GET, "/public/gallery", "/public/gallery/**").permitAll()
                        .requestMatchers(HttpMethod.GET, "/public/tags", "/public/tags/**").permitAll()
                        .requestMatchers(HttpMethod.GET, "/public/users/*/works").permitAll()
                        // 乐读派 Webhook 回调（无用户上下文，由乐读派服务端调用）
                        .requestMatchers("/webhook/leai").permitAll()
                        // Knife4j 文档
                        .requestMatchers("/doc.html", "/webjars/**", "/v3/api-docs/**", "/swagger-resources/**").permitAll()
                        // Druid 监控
                        .requestMatchers("/druid/**").permitAll()
                        // OPTIONS 预检请求
                        .requestMatchers(HttpMethod.OPTIONS, "/**").permitAll()
                        // 其余接口需要认证
                        .anyRequest().authenticated())
                // JWT 过滤器
                .addFilterBefore(jwtAuthenticationFilter, UsernamePasswordAuthenticationFilter.class);

        return http.build();
    }

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

    @Bean
    public AuthenticationManager authenticationManager(AuthenticationConfiguration config) throws Exception {
        return config.getAuthenticationManager();
    }
}
