package com.example.sjkbf.config;

import com.example.sjkbf.config.exception.CustomAuthenticationEntryPoint;
import com.example.sjkbf.service.impl.UserDetailsServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.method.configuration.EnableGlobalMethodSecurity;
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.configuration.WebSecurityConfigurerAdapter;
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.access.AccessDeniedHandlerImpl;
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;
import org.springframework.security.web.authentication.logout.LogoutFilter;
import org.springframework.web.filter.CorsFilter;

/**
 * Spring Security 核心配置类
 * - 继承 WebSecurityConfigurerAdapter（适配 Spring Boot 2.5.x）
 * - 启用方法级权限控制（@PreAuthorize）
 * - 配置 JWT 过滤器、密码加密、认证规则等
 */
@Configuration
@EnableWebSecurity
@EnableGlobalMethodSecurity(prePostEnabled = true) // 启用方法级权限注解
public class SecurityConfig extends WebSecurityConfigurerAdapter {

    @Autowired
    private UserDetailsServiceImpl userDetailsService; // 用户服务（需自行实现）

    @Autowired
    private JwtAuthenticationTokenFilter jwtAuthenticationTokenFilter; // JWT 过滤器

    @Autowired
    private CorsFilter corsFilter; // 跨域过滤器（需自行配置）

    // 认证失败处理器
    @Autowired
    private CustomAuthenticationEntryPoint unauthorizedHandler;


//    @Autowired
//    private LogoutSuccessHandlerImpl logoutSuccessHandler; // 注销成功处理器

    /**
     * 密码加密器（强制使用 BCrypt）
     */
    @Bean
    public PasswordEncoder passwordEncoder() {
        return new BCryptPasswordEncoder();
    }

    /**
     * 认证管理器（暴露为 Bean，供登录接口调用）
     */
    @Bean
    @Override
    public AuthenticationManager authenticationManagerBean() throws Exception {
        return super.authenticationManagerBean();
    }

    /**
     * 配置用户认证来源（如数据库）
     */
    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
        //注册验证用户的处理器 和密码加密器
        auth.userDetailsService(userDetailsService)
            .passwordEncoder(passwordEncoder());
    }

    /**
     * 核心安全配置
     */
    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http
            // ==================== 基础配置 ====================
            .csrf().disable() // 关闭 CSRF（REST API 无状态，无需 CSRF）
            .sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS) // 无状态会话
            .and()
            .exceptionHandling()
                .authenticationEntryPoint(unauthorizedHandler) // 认证失败处理（如未登录访问受保护接口）
                .accessDeniedHandler(new AccessDeniedHandlerImpl()) // 权限不足处理（已登录但无权限）
            .and()

            // ==================== 授权规则 ====================
            .authorizeRequests()
                // 开放接口（无需认证）
                .antMatchers(
                    "/login", 
                    "/register",
                    "/changePassword",
                    "/dps/*",
                    "/dps/*/*",
                    "/rindro/download",
                    "/rindro/download/*",
                    "/rindro/mp4",
                    "/rindro/getversion",
                    "/rindro/addgold",
                    "/rindro/getimg/*/*",
                        "/rindro/getthumb/*/*",

                        "/rindro/getmp4/*/*",
                    "/rindro/getmp42/*/*",
                    "/script/*",
                    "/api/videos/*/*",
                    "/zf/callback",
                        "/rindro/download/*/*"
                ).permitAll()
                // 其他所有请求需认证
                .anyRequest().authenticated()
            .and()

            // ==================== 过滤器配置 ====================

            // 添加 CORS 过滤器在最前
           .addFilterBefore(corsFilter, LogoutFilter.class)
            // 添加 JWT 过滤器在登录认证过滤器之前
            .addFilterBefore(jwtAuthenticationTokenFilter, UsernamePasswordAuthenticationFilter.class);


            // ==================== 注销配置 ====================
//            .logout()
//                .logoutUrl("/logout") // 注销接口
//                .logoutSuccessHandler(logoutSuccessHandler) // 注销成功处理（返回 JSON）
//                .deleteCookies("JSESSIONID"); // 删除 Cookie（如果使用）
    }
}