package com.starry.admin.common.security.config;

import com.starry.admin.common.security.filter.ApiTestAuthenticationFilter;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Profile;
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.authentication.UsernamePasswordAuthenticationFilter;

@Configuration
@EnableWebSecurity
@EnableGlobalMethodSecurity(prePostEnabled = true)
@Profile("apitest")
@EnableConfigurationProperties(ApiTestSecurityProperties.class)
public class ApiTestSecurityConfig extends WebSecurityConfigurerAdapter {

    private final ApiTestSecurityProperties properties;

    public ApiTestSecurityConfig(ApiTestSecurityProperties properties) {
        this.properties = properties;
    }

    @Bean
    public ApiTestAuthenticationFilter apiTestAuthenticationFilter() {
        return new ApiTestAuthenticationFilter(properties);
    }

    @Bean
    public PasswordEncoder passwordEncoder() {
        return new BCryptPasswordEncoder();
    }

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http.csrf().disable()
                .formLogin().disable()
                .logout().disable()
                .sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS).and()
                .authorizeRequests().anyRequest().authenticated().and()
                .addFilterBefore(apiTestAuthenticationFilter(), UsernamePasswordAuthenticationFilter.class);
    }
}
