package com.zjrs.zwnw.config;

import org.mohrss.leaf.auth.exception.LeafAuthExceptionEntryPoint;
import org.mohrss.leaf.auth.handler.LeafAccessDeniedHandler;
import org.mohrss.leaf.auth.properties.LeafOAuth2ResourceProperties;
import org.mohrss.leaf.auth.security.LeafFilterSecurityInterceptor;
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.web.SecurityFilterChain;
import org.springframework.security.web.access.intercept.AuthorizationFilter;

@Configuration
@EnableWebSecurity // 替代旧版的 @EnableResourceServer
public class ResourceConfig {

    @Autowired(required = false)
    private LeafFilterSecurityInterceptor leafFilterSecurityInterceptor;

    @Autowired
    private LeafOAuth2ResourceProperties leafOAuth2ResourceProperties;

    @Autowired
    private LeafAccessDeniedHandler leafAccessDeniedHandler;

    @Bean
    public SecurityFilterChain securityFilterChain(HttpSecurity http) throws Exception {
        http
                // 1. 禁用 CSRF 并设置无状态 Session
                .csrf(csrf -> csrf.disable())
                .sessionManagement(session -> session.sessionCreationPolicy(SessionCreationPolicy.STATELESS))

                // 2. 异常处理
                .exceptionHandling(exceptions -> exceptions
                        .authenticationEntryPoint(new LeafAuthExceptionEntryPoint())
                        .accessDeniedHandler(leafAccessDeniedHandler)
                )

                // 3. 资源访问权限配置
                .authorizeHttpRequests(auth -> auth
                        // 动态白名单配置
                        .requestMatchers(leafOAuth2ResourceProperties.getUrl().getWhitelist().toArray(new String[0])).permitAll()
                        // 其余所有请求都需要认证
                        .anyRequest().authenticated()
                )

                // 4. 开启 OAuth2 资源服务器配置 (Spring Security 6 标准写法)
                .oauth2ResourceServer(oauth2 -> oauth2
                        .jwt(jwt -> {}) // 如果是 JWT 校验模式
                        .authenticationEntryPoint(new LeafAuthExceptionEntryPoint())
                        .accessDeniedHandler(leafAccessDeniedHandler)
                );

        // 5. 插入自定义过滤器（方法级鉴权/Leaf 增强逻辑）
        // 在 Spring Security 6 中，旧的 FilterSecurityInterceptor 对应的是 AuthorizationFilter
        if (leafOAuth2ResourceProperties.getJwt().isServiceAuthenticationEnabled()
                && leafFilterSecurityInterceptor != null) {
            http.addFilterAfter(leafFilterSecurityInterceptor, AuthorizationFilter.class);
        }

        return http.build();
    }
}
