package link.at17.mid.tushare.config;

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.authentication.ProviderManager;
import org.springframework.security.authentication.dao.DaoAuthenticationProvider;
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.configurers.CsrfConfigurer;
import org.springframework.security.config.http.SessionCreationPolicy;
import org.springframework.security.crypto.password.NoOpPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.security.web.SecurityFilterChain;
import link.at17.mid.tushare.web.service.AuthService;
import lombok.RequiredArgsConstructor;

@Configuration
@EnableWebSecurity
@RequiredArgsConstructor
public class SecurityConfig {

    private final AuthService userDetailsService;

    @Bean
    public SecurityFilterChain securityFilterChain(HttpSecurity http) throws Exception {
        http
            .headers(headers -> headers
                .cacheControl(cache -> cache.disable())
                .frameOptions(frame -> frame.sameOrigin()))
            .csrf(CsrfConfigurer::disable)
            .sessionManagement(session -> session.sessionCreationPolicy(SessionCreationPolicy.IF_REQUIRED))
            .authorizeHttpRequests(auth -> auth
                .requestMatchers("/admin/res/**").permitAll()
                .requestMatchers("/favicon.ico").permitAll()
                .requestMatchers("/captcha/**").permitAll()
                .requestMatchers("/api/**").permitAll()
                .requestMatchers("/admin/login").permitAll()

                // 静态资源
                .requestMatchers("/js/**").permitAll().requestMatchers("/css/**").permitAll()
                .requestMatchers("/images/**").permitAll().anyRequest().authenticated())
            .formLogin(form -> form // 开启表单登录，并指定登录页
                .loginPage("/admin/login") // 指定登录页
                .loginProcessingUrl("/admin/doLogin") // 处理登录请求的 URL
                .defaultSuccessUrl("/admin/manage", false) // 登录成功后默认跳转
                .permitAll())
            .logout(logout -> logout.logoutUrl("/admin/logout").logoutSuccessUrl("/admin/login")
                .invalidateHttpSession(true).permitAll());
        ;

        return http.build();
    }

    @Bean
    public AuthenticationManager authenticationManager(@Autowired PasswordEncoder passwordEncoder) {
        DaoAuthenticationProvider provider = new DaoAuthenticationProvider();
        provider.setUserDetailsService(userDetailsService);
        provider.setPasswordEncoder(passwordEncoder);
        return new ProviderManager(provider);
    }

    @SuppressWarnings("deprecation")
    @Bean
    public PasswordEncoder passwordEncoder() {
        return NoOpPasswordEncoder.getInstance();
    }
}