package com.kxs.common.security.service;


import com.kxs.common.core.constant.SecurityConstants;
import com.kxs.common.core.constant.enums.ErrorTypeEnum;
import com.kxs.common.core.constant.enums.UserStatusEnum;
import com.kxs.common.core.exception.GlobalCustomerException;
import com.kxs.common.core.util.R;
import com.kxs.common.core.util.RetOps;
import com.kxs.common.security.model.KxsSecurityUser;
import com.kxs.user.api.feign.RemoteKxsUserService;
import com.kxs.user.api.model.KxsUser;
import lombok.RequiredArgsConstructor;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import org.springframework.security.authentication.InternalAuthenticationServiceException;
import org.springframework.security.authentication.LockedException;
import org.springframework.security.core.authority.AuthorityUtils;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UsernameNotFoundException;

import java.util.Objects;

/**
 * 客小爽 app用户服务实现
 *
 * @author Lxq
 * @date 2023-12-06
 */
@Slf4j
@RequiredArgsConstructor
public class KxsAppUserServiceImpl implements KxsUserDetailsService{

    private final RemoteKxsUserService remoteKxsUserService;

    @Override
    @SneakyThrows
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {

        R<KxsUser> result = remoteKxsUserService.loadUserByPhone(username, SecurityConstants.FROM_IN);
        KxsUser custom = RetOps.of(result)
                .getData()
                .orElseThrow(() -> new UsernameNotFoundException(ErrorTypeEnum.USER_NOT_FOUND.getDescription()));

        if(Objects.equals(custom.getStatus(), UserStatusEnum.REMOVE.getCode())){
            throw new UsernameNotFoundException(ErrorTypeEnum.ACCOUNT_DISABLED.getDescription());
        }
        if(Objects.equals(custom.getStatus(), UserStatusEnum.LOCKED.getCode())){
            throw new LockedException(ErrorTypeEnum.ACCOUNT_LOCKED.getDescription());
        }
        // 构造security用户
        return new KxsSecurityUser(Long.valueOf(custom.getId()), custom.getPhone(), SecurityConstants.BCRYPT + custom.getPassword(), custom.getPhone(), custom.getSalt(), true, true,
                true, !custom.getStatus().equals(UserStatusEnum.LOCKED.getCode()), AuthorityUtils.NO_AUTHORITIES);

    }

    /**
     * 是否支持此客户端校验
     * @param clientId 目标客户端
     * @param grantType  授权类型
     * @return true/false
     */
    @Override
    public boolean support(String clientId, String grantType) {
        return "kxs_app".equals(clientId);
    }

    @Override
    public int getOrder() {
        return Integer.MIN_VALUE + 1;
    }


}
