package enea.lecservice.security;

import enea.lecservice.security.dto.UserInfo;
import lombok.NonNull;
import lombok.RequiredArgsConstructor;
import lombok.extern.log4j.Log4j2;

import org.springframework.beans.factory.annotation.Autowired;
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.stereotype.Component;

import java.util.Collections;
import java.util.Optional;

@Log4j2
@Component
@RequiredArgsConstructor
public class UsernamePasswordAuthenticationProvider implements AuthenticationProvider {

    protected @NonNull InMemoryUserInfoService inMemoryUserInfoService;
    protected @NonNull IUserInfoService userInfoService;

    @Override
    public Authentication authenticate(Authentication authentication) throws AuthenticationException {
        
        String password = authentication.getCredentials().toString();
        Optional<UserInfo> userInfo ;
        if (password == null || password.length() == 0) {
        	  
         	String token = authentication.getName();
        	userInfo = userInfoService.getUserInfo(token);
        }else {
        	String username = authentication.getName();
        	userInfo = userInfoService.getUserInfo(username, password);
        }
        
        if (userInfo.isPresent()) {
            var user = new UsernamePasswordAuthenticationToken(userInfo.get(), null, userInfo.get().getAuthorities());
            inMemoryUserInfoService.createRemovingIfExists((UserInfo) user.getPrincipal());
            return user;
        } else {
            throw new BadCredentialsException("Autenticazione fallita per l'utente ");
        }
    }

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