package com.lingyue.auth.config;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.HttpMethod;
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.http.SessionCreationPolicy;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.web.SecurityFilterChain;

/**
 * Spring Security 配置
 *
 * @author lingyue
 */
@EnableMethodSecurity(prePostEnabled = true, securedEnabled = true)
@Configuration
@EnableWebSecurity
public class SecurityConfig {
    
    /**
     * 安全过滤器链配置
     */
    @Bean
    public SecurityFilterChain securityFilterChain(HttpSecurity httpSecurity) throws Exception {
        return httpSecurity
                // CSRF禁用，因为不使用session
                .csrf(csrf -> csrf.disable())
                // 禁用HTTP响应标头
                .headers((headersCustomizer) -> {
                    headersCustomizer.cacheControl(cache -> cache.disable())
                                     .frameOptions(options -> options.sameOrigin());
                })
                // 基于token，所以不需要session
                .sessionManagement(session -> session.sessionCreationPolicy(SessionCreationPolicy.STATELESS))
                // 授权配置
                .authorizeHttpRequests((requests) -> {
                    // 对于登录、注册、刷新Token、用户信息允许匿名访问
                    requests.requestMatchers("/auth/**").permitAll()
                            // 文档接口（开发阶段暂时开放）
                            .requestMatchers("/api/v1/documents/**").permitAll()
                            // 知识图谱接口（开发阶段暂时开放）
                            .requestMatchers("/api/v1/graph/**").permitAll()
                            // 结构化文档接口（开发阶段暂时开放）
                            .requestMatchers("/api/v1/ner/**").permitAll()
                            // Actuator 健康检查
                            .requestMatchers("/actuator/**").permitAll()
                            // API 文档
                            .requestMatchers("/swagger-ui/**", "/v3/api-docs/**", "/swagger-resources/**").permitAll()
                            // 文件上传和解析（开发阶段暂时开放）
                            .requestMatchers("/api/v1/parse/**", "/parse/**").permitAll()
                            // RAG 接口（开发阶段暂时开放）
                            .requestMatchers("/api/rag/**").permitAll()
                            // 图谱接口（开发阶段暂时开放）
                            .requestMatchers("/api/graph/**", "/api/text-storage/**").permitAll()
                            // 静态资源，可匿名访问
                            .requestMatchers(HttpMethod.GET,
                                             "/",
                                             "/*.html",
                                             "/**/*.html",
                                             "/**/*.css",
                                             "/**/*.js").permitAll()
                            // 错误页面
                            .requestMatchers("/error").permitAll()
                            // 除上面外的所有请求全部需要鉴权认证
                            .anyRequest().authenticated();
                })
                .build();
    }
    
    /**
     * 强散列哈希加密实现
     */
    @Bean
    public BCryptPasswordEncoder bCryptPasswordEncoder() {
        return new BCryptPasswordEncoder();
    }
}

