package @app.group.id@.@app.name@.security;

import org.springframework.boot.web.servlet.FilterRegistrationBean;
import org.springframework.context.annotation.Bean;
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.web.SecurityFilterChain;

import jakarta.servlet.DispatcherType;
import jakarta.servlet.Filter;
import java.util.Collections;

@EnableWebSecurity
public class SecurityConfig {

    @Bean
    public SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
        http.authorizeHttpRequests((authz) -> authz
                .requestMatchers(HttpMethod.DELETE, "/api/buildings")
                .hasRole("ADMIN")
                .anyRequest()
                .permitAll()
                );
        return http.build();
    }

    @Bean
    public FilterRegistrationBean csrfPreventionFilter() {
        FilterRegistrationBean<Filter> registration = new FilterRegistrationBean<>();
        registration.setFilter(new CsrfPreventionFilter());
        registration.setUrlPatterns(Collections.singleton("/api/*"));
        registration.setDispatcherTypes(DispatcherType.REQUEST);

        return registration;
    }

    @Bean
    public FilterRegistrationBean cachingPreventionFilter() {
        FilterRegistrationBean<Filter> registration = new FilterRegistrationBean<>();
        registration.setFilter(new CachingPreventionFilter());
        registration.setUrlPatterns(Collections.singleton("/api/*"));
        registration.setDispatcherTypes(DispatcherType.REQUEST);

        return registration;
    }
}
