package com.ankurm.authdemo.auth;

import org.springframework.security.authentication.AuthenticationProvider;
import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.core.authority.FactorGrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.crypto.password.PasswordEncoder;

import java.util.List;
import java.util.Map;

/**
 * Same contract as CustomAuthProvider, but compares hashes instead of plain text.
 * Throws BadCredentialsException for an unknown user or a wrong password, so the
 * ProviderManager moves on to the next provider (see ProviderManagerSemanticsTests).
 */
public class EncodedCustomAuthProvider implements AuthenticationProvider {

    private final PasswordEncoder passwordEncoder;

    // Stand-in for a real lookup (DB, legacy API, ...). Passwords are hashes,
    // never plain text.
    private final Map<String, String> encodedPasswordsByUsername;

    public EncodedCustomAuthProvider(PasswordEncoder passwordEncoder,
                                     Map<String, String> encodedPasswordsByUsername) {
        this.passwordEncoder = passwordEncoder;
        this.encodedPasswordsByUsername = encodedPasswordsByUsername;
    }

    @Override
    public Authentication authenticate(Authentication authentication) throws AuthenticationException {
        String username = authentication.getName();
        String rawPassword = authentication.getCredentials().toString();

        String encoded = encodedPasswordsByUsername.get(username);
        if (encoded == null || !passwordEncoder.matches(rawPassword, encoded)) {
            throw new BadCredentialsException("Invalid credentials provided");
        }

        // Credentials are null on purpose: finish all password handling in this method.
        // The PASSWORD factor records HOW the user proved who they are (used by the MFA rule).
        return UsernamePasswordAuthenticationToken.authenticated(username, null,
                List.of(new SimpleGrantedAuthority("ROLE_USER"),
                        FactorGrantedAuthority.fromAuthority(FactorGrantedAuthority.PASSWORD_AUTHORITY)));
    }

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