package com.ningdatech.kqapi.security.facade;

import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.ningdatech.kqapi.common.constant.BizConst;
import com.ningdatech.kqapi.security.constant.AuthTypeEnum;
import com.ningdatech.kqapi.user.model.entity.UserAuth;
import com.ningdatech.kqapi.user.model.entity.UserInfo;
import com.ningdatech.kqapi.security.model.dto.UserInfoBO;
import com.ningdatech.kqapi.user.service.IUserAuthService;
import com.ningdatech.kqapi.user.service.IUserInfoService;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Component;

import java.util.Arrays;
import java.util.List;
import java.util.Objects;

/**
 * <p>
 * UserAuthLoginFacade
 * </p>
 *
 * @author WendyYang
 * @since 10:14 2024/4/20
 */
@Component
@RequiredArgsConstructor
public class UserAuthLoginFacade {

    private final IUserAuthService userAuthService;
    private final IUserInfoService userInfoService;

    private static final List<AuthTypeEnum> AUTH_TYPES = Arrays.asList(AuthTypeEnum.ACCOUNT_PASSWORD,
            AuthTypeEnum.PHONE_PASSWORD);


    public UserInfoBO queryUserInfoInPasswordAuth(String username) {
        // 获取用户鉴权信息
        UserAuth userAuth = userAuthService.getOne(Wrappers.lambdaQuery(UserAuth.class)
                .eq(UserAuth::getIdentifier, username)
                .in(UserAuth::getAuthType, AUTH_TYPES)
                .last(BizConst.LIMIT_1));
        if (Objects.isNull(userAuth)) {
            return null;
        }
        //  获取用户详情信息
        Long userId = userAuth.getUserId();
        UserInfo userInfo = userInfoService.getById(userId);
        UserInfoBO user = new UserInfoBO();
        user.setAccountStatus(userInfo.getAccountStatus());
        user.setUserId(userInfo.getId());
        user.setRealName(userInfo.getRealName());
        user.setUsername(userInfo.getUsername());
        user.setRole(userInfo.getRole());
        user.setIdentifier(userAuth.getIdentifier());
        user.setCredential(userAuth.getCredential());
        return user;
    }
}
