package com.ankurm.authdemo;

import org.junit.jupiter.api.Test;
import org.springframework.security.authentication.*;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;

import java.util.List;
import java.util.function.Supplier;

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

/** Pure unit tests: how does ProviderManager treat each answer a provider can give? */
class ProviderManagerSemanticsTests {

    private static final Authentication LOGIN = new UsernamePasswordAuthenticationToken("alice", "pw");
    private final Transcript t = new Transcript("01-provider-manager-semantics");

    /** A provider whose answer we control. */
    private static AuthenticationProvider provider(String name, Supplier<Authentication> answer) {
        return new AuthenticationProvider() {
            @Override
            public Authentication authenticate(Authentication a) throws AuthenticationException {
                return answer.get();
            }

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

            @Override
            public String toString() {
                return name;
            }
        };
    }

    private static Authentication ok(String who) {
        return UsernamePasswordAuthenticationToken.authenticated(who, null, List.of());
    }

    private static <E extends AuthenticationException> Supplier<Authentication> throwing(E ex) {
        return () -> {
            throw ex;
        };
    }

    private String run(List<AuthenticationProvider> providers) {
        try {
            Authentication result = new ProviderManager(providers).authenticate(LOGIN);
            return "authenticated as " + result.getName();
        } catch (AuthenticationException ex) {
            return "failed with " + ex.getClass().getSimpleName();
        }
    }

    @Test
    void whatEachAnswerMeans() {
        String badThenOk = run(List.of(
                provider("A", throwing(new BadCredentialsException("no"))), provider("B", () -> ok("from-B"))));
        String lockedThenOk = run(List.of(
                provider("A", throwing(new LockedException("locked"))), provider("B", () -> ok("from-B"))));
        String serviceThenOk = run(List.of(
                provider("A", throwing(new AuthenticationServiceException("down"))), provider("B", () -> ok("from-B"))));
        String internalThenOk = run(List.of(
                provider("A", throwing(new InternalAuthenticationServiceException("down"))), provider("B", () -> ok("from-B"))));
        String nullThenOk = run(List.of(provider("A", () -> null), provider("B", () -> ok("from-B"))));
        String allNull = run(List.of(provider("A", () -> null), provider("B", () -> null)));
        String badThenNull = run(List.of(
                provider("A", throwing(new BadCredentialsException("no"))), provider("B", () -> null)));

        t.line("Provider A answers, then provider B answers. What does ProviderManager return?");
        t.line("A throws BadCredentialsException, B succeeds                  -> %s", badThenOk);
        t.line("A throws AuthenticationServiceException, B succeeds           -> %s", serviceThenOk);
        t.line("A throws LockedException, B succeeds                          -> %s", lockedThenOk);
        t.line("A throws InternalAuthenticationServiceException, B succeeds   -> %s", internalThenOk);
        t.line("A returns null, B succeeds                                    -> %s", nullThenOk);
        t.line("A throws BadCredentialsException, B returns null              -> %s", badThenNull);
        t.line("A returns null, B returns null                                -> %s", allNull);
        t.write();

        assertThat(badThenOk).isEqualTo("authenticated as from-B");
        assertThat(serviceThenOk).isEqualTo("authenticated as from-B");
        assertThat(nullThenOk).isEqualTo("authenticated as from-B");
        assertThat(lockedThenOk).isEqualTo("failed with LockedException");
        assertThat(internalThenOk).isEqualTo("failed with InternalAuthenticationServiceException");
        assertThat(badThenNull).isEqualTo("failed with BadCredentialsException");
        assertThat(allNull).isEqualTo("failed with ProviderNotFoundException");
    }

    @Test
    void credentialsAreErasedAfterSuccess() {
        Authentication fromProvider = new UsernamePasswordAuthenticationToken(
                "alice", "still-the-raw-password", List.of());
        Object before = fromProvider.getCredentials();
        Authentication result = new ProviderManager(provider("A", () -> fromProvider)).authenticate(LOGIN);

        Transcript t = new Transcript("08-credentials-erased");
        t.line("provider returned a token carrying credentials = %s", before);
        t.line("after ProviderManager.authenticate(): credentials = %s", result.getCredentials());
        t.write();

        assertThat(before).isEqualTo("still-the-raw-password");
        assertThat(result.getCredentials()).isNull();
    }

    @Test
    void providerThatDoesNotSupportTheTokenIsNeverCalled() {
        AuthenticationProvider picky = new AuthenticationProvider() {
            @Override
            public Authentication authenticate(Authentication a) {
                throw new AssertionError("must not be called");
            }

            @Override
            public boolean supports(Class<?> type) {
                return false;
            }
        };
        assertThatThrownBy(() -> new ProviderManager(picky).authenticate(LOGIN))
                .isInstanceOf(ProviderNotFoundException.class);
    }
}
