package com.yupi.project.config;

import com.yupi.project.model.enums.UserRoleEnum;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.HttpMethod;
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.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.web.cors.CorsConfiguration;
import org.springframework.web.cors.CorsConfigurationSource;
import org.springframework.web.cors.UrlBasedCorsConfigurationSource;

import java.util.Arrays;
import java.util.Collections;

/**
 * 安全相关配置 (集成CORS)
 */
@Configuration
@EnableWebSecurity // 启用Spring Security的Web安全支持
public class SecurityConfig extends WebSecurityConfigurerAdapter {

    @Bean
    public PasswordEncoder passwordEncoder() {
        // 使用 BCrypt 进行密码加密
        return new BCryptPasswordEncoder();
    }

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http
            // 集成CORS配置
            .cors()
            .and()
            // 明确禁用CSRF保护
            .csrf().disable()
            .authorizeRequests(
                // 允许对登录和注册接口的匿名访问 (路径不带 /api 前缀)
                authorize -> authorize
                    .antMatchers("/user/login", "/user/register", "/error").permitAll()
                    .antMatchers("/user/current").authenticated()
                    // 使用 hasAuthority 确保匹配 UserRoleEnum.ADMIN.getValue() 即 "admin"
                    .antMatchers("/user/list").hasAuthority(UserRoleEnum.ADMIN.getValue())
                    .antMatchers(HttpMethod.DELETE, "/user/delete/**").hasAuthority(UserRoleEnum.ADMIN.getValue())
                    .antMatchers(HttpMethod.POST, "/user/admin/add").hasAuthority(UserRoleEnum.ADMIN.getValue())
                    .antMatchers(HttpMethod.PUT, "/user/admin/update").hasAuthority(UserRoleEnum.ADMIN.getValue())
                    // 明确允许 /admin/robot 相关请求
                    .antMatchers("/admin/robot/**").hasAuthority(UserRoleEnum.ADMIN.getValue())
                    // 其他所有请求都需要认证
                    .anyRequest().authenticated()
            )
            // 禁用默认的表单登录页面
            .formLogin().disable()
            // 禁用HTTP Basic认证
            .httpBasic().disable();
    }

    @Bean
    CorsConfigurationSource corsConfigurationSource() {
        CorsConfiguration configuration = new CorsConfiguration();
        // 允许所有源，更宽松的配置
        configuration.setAllowedOriginPatterns(Collections.singletonList("*"));
        // 允许所有HTTP方法
        configuration.setAllowedMethods(Arrays.asList("GET", "POST", "PUT", "PATCH", "DELETE", "OPTIONS", "HEAD"));
        // 允许所有头
        configuration.setAllowedHeaders(Collections.singletonList("*"));
        // 允许发送凭证（cookies、HTTP认证及客户端SSL证明等）
        configuration.setAllowCredentials(true);
        // 预检请求的有效期，单位为秒
        configuration.setMaxAge(3600L);
        // 暴露响应头，特别是授权相关的
        configuration.setExposedHeaders(Arrays.asList("Authorization", "Set-Cookie", "X-XSRF-TOKEN"));
        
        UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
        // 对所有路径应用配置
        source.registerCorsConfiguration("/**", configuration);
        return source;
    }
} 