package org.lingniu.idp.security.provider;

import org.lingniu.idp.model.dto.LoginUser;
import org.lingniu.idp.security.token.MobilePasswordAuthenticationToken;
import org.lingniu.idp.service.core.login.LoginService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.AuthenticationProvider;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.stereotype.Component;

import java.util.Collections;

@Component
public class MobilePasswordAuthenticationProvider implements AuthenticationProvider {
    
    @Autowired
    private UserDetailsService userDetailsService;
    @Autowired
    private LoginService loginService;
    
    @Override
    public Authentication authenticate(Authentication authentication) throws AuthenticationException {
        MobilePasswordAuthenticationToken authToken = (MobilePasswordAuthenticationToken) authentication;
        String username = (String) authToken.getPrincipal();
        String password = (String) authToken.getCredentials();
        String code = authToken.getCode();
        String uuid = authToken.getUuid();

        // 2. 加载用户
        LoginUser login = loginService.login(username, password, code, uuid);

        // 3. 返回认证成功的Token
        return new MobilePasswordAuthenticationToken(
                login,
            null
        );
    }
    
    @Override
    public boolean supports(Class<?> authentication) {
        return MobilePasswordAuthenticationToken.class.isAssignableFrom(authentication);
    }
}