package com.ankurm.authdemo.config;

import com.ankurm.authdemo.auth.CustomAuthProvider;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Profile;
import org.springframework.core.annotation.Order;
import org.springframework.security.config.Customizer;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.oauth2.jwt.JwtDecoder;
import org.springframework.security.web.SecurityFilterChain;

@Configuration
@EnableWebSecurity
@Profile("multichain")
public class MultiChainSecurityConfig {

    @Bean
    public CustomAuthProvider customAuthProvider() {
        return new CustomAuthProvider();
    }

    // Chain 1: JWT-secured API. The bearer-token filter is authenticated by a
    // JwtAuthenticationProvider that oauth2ResourceServer() builds internally --
    // it never touches the shared AuthenticationManager, so it is unaffected by
    // whatever AuthenticationProvider beans exist elsewhere in the context.
    @Bean
    @Order(1)
    public SecurityFilterChain apiFilterChain(HttpSecurity http, JwtDecoder jwtDecoder) throws Exception {
        http
            .securityMatcher("/api/**")
            .authorizeHttpRequests(auth -> auth.anyRequest().authenticated())
            .oauth2ResourceServer(oauth2 -> oauth2.jwt(jwt -> jwt.decoder(jwtDecoder)))
            .csrf(csrf -> csrf.disable());

        return http.build();
    }

    // Chain 2: everything else, authenticated by CustomAuthProvider via form login.
    // Attaching the provider explicitly -- rather than counting on it being the
    // only AuthenticationProvider bean in the context -- keeps it scoped to this
    // chain even if a second provider bean shows up later.
    @Bean
    @Order(2)
    public SecurityFilterChain webFilterChain(HttpSecurity http) throws Exception {
        http
            .authenticationProvider(customAuthProvider())
            .authorizeHttpRequests(auth -> auth
                .requestMatchers("/public/**").permitAll()
                .requestMatchers("/admin/**").hasRole("ADMIN")
                .anyRequest().authenticated()
            )
            .formLogin(Customizer.withDefaults());

        return http.build();
    }
}
