package com.xingxi.api.configuration.security;

import cn.binarywang.wx.miniapp.api.WxMaService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import me.chanjar.weixin.mp.api.WxMpService;
import org.springframework.beans.factory.annotation.Value;
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.builders.WebSecurity;
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.web.authentication.UsernamePasswordAuthenticationFilter;
import org.springframework.web.cors.CorsConfiguration;
import org.springframework.web.cors.CorsConfigurationSource;
import org.springframework.web.cors.UrlBasedCorsConfigurationSource;

import java.util.Arrays;

@Slf4j
@Configuration
@EnableWebSecurity
@RequiredArgsConstructor
class SpringWebSecurityConfiguration extends WebSecurityConfigurerAdapter {
    @Value("${spring.application.cors.pathPattern}")
    private String pathPattern;
    @Value("${spring.application.cors.allowedMethods}")
    private String[] allowedMethods;
    @Value("${spring.application.cors.allowedOrigins}")
    private String[] allowedOrigins;
    @Value("${spring.application.cors.allowedHeaders}")
    private String[] allowedHeaders;

    private final JwtAuthenticationManager jwtAuthenticationManager;
    private final WxLoginAuthenticationManager wxLoginAuthenticationManager;
    private final WxAuthenticationSuccessHandler wxAuthenticationSuccessHandler;
    private final WxAuthenticationFailureHandler wxAuthenticationFailureHandler;
    private final WxAuthenticationEntryPoint wxAuthenticationEntryPoint;
    private final WxAccessDeniedHandler wxAccessDeniedHandler;
    private final WxMaService wxMaService;
    private final WxMpService wxMpService;

    // cors
    @Bean("corsConfigurationSource")
    public CorsConfigurationSource corsConfigurationSource() {
        CorsConfiguration configuration = new CorsConfiguration();
        configuration.setAllowedOrigins(Arrays.asList(allowedOrigins));
        configuration.setAllowedMethods(Arrays.asList(allowedMethods));
        configuration.setAllowedHeaders(Arrays.asList(allowedHeaders));
        UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
        source.registerCorsConfiguration(pathPattern, configuration);
        return source;
    }
    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http.csrf()
                .disable()
                .sessionManagement()
                .sessionCreationPolicy(SessionCreationPolicy.STATELESS)
                .and()
                .cors()
                .and()
                .authorizeRequests()
                .antMatchers("/error/**", "/unifiedpay/**").permitAll()
                .anyRequest().authenticated()
                .and()
                .exceptionHandling()
                .authenticationEntryPoint(wxAuthenticationEntryPoint)
                .accessDeniedHandler(wxAccessDeniedHandler);
        // 使用WxAppletAuthenticationFilter替换默认的认证过滤器UsernamePasswordAuthenticationFilter


        http.addFilterAt(wxLoginAuthenticationProcessingFilter(), UsernamePasswordAuthenticationFilter.class)
                // 在WxAppletAuthenticationFilter前面添加用于验证jwt，识别用户是否登录的过滤器
                .addFilterBefore(jwtAuthenticationTokenFilter(), WxLoginAuthenticationProcessingFilter.class);
    }

    @Bean
    public JwtAuthenticationFilter jwtAuthenticationTokenFilter() {
        log.debug("JwtAuthenticationFilter created.");
        return new JwtAuthenticationFilter(jwtAuthenticationManager);
    }

    @Bean
    public WxLoginAuthenticationProcessingFilter wxLoginAuthenticationProcessingFilter() {
        log.debug("WxLoginAuthenticationProcessingFilter created.");
        WxLoginAuthenticationProcessingFilter filter = new WxLoginAuthenticationProcessingFilter(wxLoginAuthenticationManager, wxMaService, wxMpService);
        filter.setAuthenticationSuccessHandler(wxAuthenticationSuccessHandler);
        filter.setAuthenticationFailureHandler(wxAuthenticationFailureHandler);
        return filter;
    }

    @Override
    public void configure(WebSecurity web) throws Exception {
        web.ignoring().antMatchers("/api/store/wxlogin", "/wxpay/**");
    }
}
