package com.hz.pm.api.user.security.auth.code;


import com.hz.pm.api.common.helper.UserInfoHelper;
import com.hz.pm.api.user.convert.UserInfoConvertor;
import com.hz.pm.api.user.model.enumeration.UserAvailableEnum;
import com.hz.pm.api.user.security.model.UserFullInfoDTO;
import com.hz.pm.api.user.security.model.UserInfoDetails;
import com.hz.pm.api.user.security.validate.CommonLoginException;
import lombok.RequiredArgsConstructor;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import java.util.Objects;

/**
 * <p>
 * AuthCodeLoginUserDetailService
 * </p>
 *
 * @author WendyYang
 * @since 15:57 2024/1/4
 */
@Service("authCodeLoginUserDetailService")
@RequiredArgsConstructor
public class AuthCodeLoginUserDetailService implements UserDetailsService {

    private final UserInfoHelper userInfoHelper;

    @Override
    public UserInfoDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        Long userId = Long.parseLong(username);
        UserFullInfoDTO ufi = userInfoHelper.getUserFullInfo(userId);
        if (Objects.isNull(ufi)) {
            throw new UsernameNotFoundException("用户不存在");
        }
        if (UserAvailableEnum.DISABLE.equals(ufi.getAvailable())) {
            throw new CommonLoginException("账号已禁用");
        }
        return UserInfoConvertor.convert(ufi);
    }

}
