package org.fuseri.moduleexercise.config;

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.configurers.oauth2.server.resource.OAuth2ResourceServerConfigurer;
import org.springframework.security.web.SecurityFilterChain;
import org.springframework.web.servlet.config.annotation.EnableWebMvc;

@Configuration
@EnableWebSecurity
@EnableWebMvc


public class AppSecurityConfig {

    @Bean
    public SecurityFilterChain filterChain(HttpSecurity httpSecurity) throws Exception {
        httpSecurity.csrf().disable();
        httpSecurity.authorizeHttpRequests(x -> x
                .requestMatchers(
                        "/actuator/**",
                        "/swagger-ui/**",
                        "/v3/api-docs/**",
                        "/datainitializer").permitAll()

                .requestMatchers(HttpMethod.POST, "/answers/**").hasAnyAuthority("SCOPE_test_1", "SCOPE_test_2")
                .requestMatchers(HttpMethod.DELETE, "/answers/**").hasAnyAuthority("SCOPE_test_1", "SCOPE_test_2")
                .requestMatchers(HttpMethod.PUT, "/answers/**").hasAnyAuthority("SCOPE_test_1", "SCOPE_test_2")

                .requestMatchers(HttpMethod.POST, "/questions/**").hasAnyAuthority("SCOPE_test_1", "SCOPE_test_2")
                .requestMatchers(HttpMethod.DELETE, "/questions/**").hasAnyAuthority("SCOPE_test_1", "SCOPE_test_2")
                .requestMatchers(HttpMethod.PUT, "/questions/**").hasAnyAuthority("SCOPE_test_1", "SCOPE_test_2")
                .requestMatchers(HttpMethod.PATCH, "/questions/**").hasAnyAuthority("SCOPE_test_1", "SCOPE_test_2")

                .requestMatchers(HttpMethod.POST, "/exercises/**").hasAnyAuthority("SCOPE_test_1", "SCOPE_test_2")
                .requestMatchers(HttpMethod.DELETE, "/exercises/**").hasAnyAuthority("SCOPE_test_1", "SCOPE_test_2")
                .requestMatchers(HttpMethod.PUT, "/exercises/**").hasAnyAuthority("SCOPE_test_1", "SCOPE_test_2")
                .anyRequest().authenticated()

        ).oauth2ResourceServer(OAuth2ResourceServerConfigurer::opaqueToken)
        ;
        return httpSecurity.build();
    }
}
