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.SimpleGrantedAuthority;

import java.util.ArrayList;
import java.util.List;

/**
 * The smallest working AuthenticationProvider. Deliberately naive: it compares
 * plain-text passwords. EncodedCustomAuthProvider is the version you would ship.
 */
public class CustomAuthProvider implements AuthenticationProvider {

    @Override
    public Authentication authenticate(Authentication authentication) throws AuthenticationException {
        // 1. Extract credentials from the authentication object
        String username = authentication.getName();
        String password = authentication.getCredentials().toString();

        // 2. VALIDATION LOGIC
        // In a real app, inject a Service or Repository here to check DB/External API
        if ("admin".equals(username) && "secret".equals(password)) {
            return createSuccessfulAuth(username, password, "ROLE_ADMIN", "ROLE_USER");
        } else if ("user".equals(username) && "password".equals(password)) {
            return createSuccessfulAuth(username, password, "ROLE_USER");
        }

        // 3. Fail explicitly if credentials don't match
        throw new BadCredentialsException("Invalid credentials provided");
    }

    // Helper method to construct the authenticated token
    private Authentication createSuccessfulAuth(String username, String password, String... roles) {
        List<SimpleGrantedAuthority> authorities = new ArrayList<>();
        for (String role : roles) {
            authorities.add(new SimpleGrantedAuthority(role));
        }
        // IMPORTANT: The third argument (authorities) marks the token as authenticated
        return new UsernamePasswordAuthenticationToken(username, password, authorities);
    }

    @Override
    public boolean supports(Class<?> authenticationType) {
        // Ensure this provider only processes standard username/password tokens
        return authenticationType.equals(UsernamePasswordAuthenticationToken.class);
    }
}
