package com.ankurm.authdemo;

import com.ankurm.authdemo.auth.CustomAuthProvider;
import com.ankurm.authdemo.web.AuthenticationAudit;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.boot.test.system.CapturedOutput;
import org.springframework.boot.test.system.OutputCaptureExtension;
import org.springframework.boot.webmvc.test.autoconfigure.AutoConfigureMockMvc;
import org.springframework.context.annotation.Bean;
import org.springframework.boot.test.context.TestConfiguration;
import org.springframework.context.annotation.Import;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.AuthenticationProvider;
import org.springframework.security.authentication.ProviderManager;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
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.core.Authentication;
import org.springframework.security.web.SecurityFilterChain;
import org.springframework.test.web.servlet.MockMvc;

import static org.assertj.core.api.Assertions.assertThat;

/** What does a chain that never calls .authenticationProvider(...) actually depend on? */
@ExtendWith(OutputCaptureExtension.class)
class WiringTests {

    /** A second provider that never authenticates anyone. Its mere existence is the point. */
    static class IdleProvider implements AuthenticationProvider {
        @Override
        public Authentication authenticate(Authentication a) {
            return null;
        }

        @Override
        public boolean supports(Class<?> type) {
            return UsernamePasswordAuthenticationToken.class.isAssignableFrom(type);
        }
    }

    static SecurityFilterChain implicitChain(HttpSecurity http) throws Exception {
        // note: no .authenticationProvider(...) here
        http.authorizeHttpRequests(a -> a.anyRequest().authenticated()).formLogin(Customizer.withDefaults());
        return http.build();
    }

    @TestConfiguration
    @EnableAutoConfiguration
    @EnableWebSecurity
    @Import(AuthenticationAudit.class)
    static class OneProviderBean {
        @Bean
        CustomAuthProvider customAuthProvider() {
            return new CustomAuthProvider();
        }

        @Bean
        SecurityFilterChain chain(HttpSecurity http) throws Exception {
            return implicitChain(http);
        }
    }

    @TestConfiguration
    @EnableAutoConfiguration
    @EnableWebSecurity
    @Import(AuthenticationAudit.class)
    static class TwoProviderBeans {
        @Bean
        CustomAuthProvider customAuthProvider() {
            return new CustomAuthProvider();
        }

        @Bean
        IdleProvider idleProvider() {
            return new IdleProvider();
        }

        @Bean
        SecurityFilterChain chain(HttpSecurity http) throws Exception {
            return implicitChain(http);
        }
    }

    @TestConfiguration
    @EnableAutoConfiguration
    @EnableWebSecurity
    @Import(AuthenticationAudit.class)
    static class TwoBeansExplicitAttach {
        @Bean
        CustomAuthProvider customAuthProvider() {
            return new CustomAuthProvider();
        }

        @Bean
        IdleProvider idleProvider() {
            return new IdleProvider();
        }

        @Bean
        SecurityFilterChain chain(HttpSecurity http, CustomAuthProvider provider) throws Exception {
            http.authenticationProvider(provider);
            return implicitChain(http);
        }
    }



    /** Accepts exactly one login, mgr/x, so we can tell WHICH manager answered. */
    static class ManagerOnlyProvider implements AuthenticationProvider {
        @Override
        public Authentication authenticate(Authentication a) {
            if ("mgr".equals(a.getName()) && "x".equals(String.valueOf(a.getCredentials()))) {
                return UsernamePasswordAuthenticationToken.authenticated("mgr", null, java.util.List.of());
            }
            return null;
        }

        @Override
        public boolean supports(Class<?> type) {
            return UsernamePasswordAuthenticationToken.class.isAssignableFrom(type);
        }
    }

    /** One provider bean AND a hand-built AuthenticationManager bean (the pattern the 2025 article used). */
    @TestConfiguration
    @EnableAutoConfiguration
    @EnableWebSecurity
    @Import(AuthenticationAudit.class)
    static class OneBeanPlusManagerBean {
        @Bean
        CustomAuthProvider customAuthProvider() {
            return new CustomAuthProvider();
        }

        @Bean
        AuthenticationManager authenticationManager() {
            return new ProviderManager(new ManagerOnlyProvider());
        }

        @Bean
        SecurityFilterChain chain(HttpSecurity http) throws Exception {
            return implicitChain(http);
        }
    }

    /** Two provider beans, rescued by a hand-built AuthenticationManager bean that lists both. */
    @TestConfiguration
    @EnableAutoConfiguration
    @EnableWebSecurity
    @Import(AuthenticationAudit.class)
    static class TwoBeansPlusManagerBean {
        @Bean
        CustomAuthProvider customAuthProvider() {
            return new CustomAuthProvider();
        }

        @Bean
        IdleProvider idleProvider() {
            return new IdleProvider();
        }

        @Bean
        AuthenticationManager authenticationManager(CustomAuthProvider a, IdleProvider b) {
            return new ProviderManager(a, b);
        }

        @Bean
        SecurityFilterChain chain(HttpSecurity http) throws Exception {
            return implicitChain(http);
        }
    }

    @Test
    void autoWireVersusExplicitAttach(CapturedOutput output) throws Exception {
        Transcript t = new Transcript("05-provider-wiring");

        String one = runScenario(OneProviderBean.class, "admin", "secret");
        String two = runScenario(TwoProviderBeans.class, "admin", "secret");
        String attached = runScenario(TwoBeansExplicitAttach.class, "admin", "secret");

        t.line("Chain never calls .authenticationProvider(...); admin/secret posted to /login");
        t.line("one AuthenticationProvider bean            -> %s", one);
        t.line("two AuthenticationProvider beans           -> %s", two);
        t.line("two beans, chain attaches CustomAuthProvider -> %s", attached);
        t.line("");
        t.line("A hand-built AuthenticationManager bean (what the 2025 article published):");
        String own1a = runScenario(OneBeanPlusManagerBean.class, "admin", "secret");
        String own1b = runScenario(OneBeanPlusManagerBean.class, "mgr", "x");
        String own2 = runScenario(TwoBeansPlusManagerBean.class, "admin", "secret");
        t.line("one provider bean + manager bean(only mgr/x)   admin/secret -> %s", own1a);
        t.line("one provider bean + manager bean(only mgr/x)   mgr/x        -> %s", own1b);
        t.line("two provider beans + manager bean listing both admin/secret -> %s", own2);
        t.line("");
        t.line("Log lines from the two-bean start-up that mention AuthenticationProvider:");
        output.getAll().lines().filter(l -> l.contains("Found ") && l.contains("AuthenticationProvider beans"))
                .map(l -> l.substring(l.indexOf("Found "))).distinct().forEach(l -> t.line("%s", l));
        t.write();

        assertThat(one).startsWith("302 -> /  ");
        assertThat(two).startsWith("302 -> /login?error");
        assertThat(attached).startsWith("302 -> /  ");
        assertThat(own1a).startsWith("302 -> /  ");
        assertThat(own1b).startsWith("302 -> /login?error");
        assertThat(own2).startsWith("302 -> /  ");
    }

    private String runScenario(Class<?> config, String user, String password) throws Exception {
        try (var ctx = new org.springframework.boot.builder.SpringApplicationBuilder(config)
                .web(org.springframework.boot.WebApplicationType.SERVLET)
                .properties("server.port=0", "spring.main.banner-mode=off")
                .run()) {
            MockMvc mvc = org.springframework.test.web.servlet.setup.MockMvcBuilders
                    .webAppContextSetup((org.springframework.web.context.WebApplicationContext) ctx)
                    .apply(org.springframework.security.test.web.servlet.setup.SecurityMockMvcConfigurers.springSecurity())
                    .build();
            var result = Logins.login(mvc, user, password);
            AuthenticationAudit audit = ctx.getBean(AuthenticationAudit.class);
            String last = audit.events().isEmpty() ? "no event" : audit.events().getLast().split(" ")[0];
            return result.describe() + "  " + last;
        }
    }
}
