package com.zjrs.ggfw.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 {
        // 1. 基础安全配置：禁用 CSRF，设置为无状态 Session
        http
                .csrf(csrf -> csrf.disable())
                .sessionManagement(session -> session.sessionCreationPolicy(SessionCreationPolicy.STATELESS));

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

        // 3. 授权规则配置
        http.authorizeHttpRequests(authorize -> authorize
                // 配置白名单
                .requestMatchers(leafOAuth2ResourceProperties.getUrl().getWhitelist().toArray(new String[0])).permitAll()
                // 其他所有请求需认证
                .anyRequest().authenticated()
        );

        // 4. 开启 OAuth2 资源服务器支持 (现代版核心配置)
        http.oauth2ResourceServer(oauth2 -> oauth2
                .jwt(jwt -> {}) // 如果是 JWT 模式
                .authenticationEntryPoint(new LeafAuthExceptionEntryPoint())
                .accessDeniedHandler(leafAccessDeniedHandler)
        );

        // 5. 插入自定义过滤器（方法级鉴权）
        if (leafOAuth2ResourceProperties.getJwt().isServiceAuthenticationEnabled()
                && leafFilterSecurityInterceptor != null) {
            // 在新的体系中，通常在 AuthorizationFilter 之后或之前添加
            http.addFilterAfter(leafFilterSecurityInterceptor, AuthorizationFilter.class);
        }

        return http.build();
    }
}