package com.xingxi.api.configuration.security;

import com.xingxi.common.core.domain.entity.SysUser;
import com.xingxi.common.utils.DateUtils;
import com.xingxi.api.common.UserContext;
import com.xingxi.system.mapper.SysUserMapper;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;
import org.springframework.stereotype.Component;
import org.springframework.util.ObjectUtils;

import java.util.ArrayList;
import java.util.Date;

@Slf4j
@RequiredArgsConstructor
@Component("JwtAuthenticationManager")
class JwtAuthenticationManager implements AuthenticationManager {
    private final SysUserMapper sysUserMapper;

    @Override
    public Authentication authenticate(Authentication authentication) throws AuthenticationException {
        log.debug("JwtAuthenticationManager.authenticate()....");
        Date now = DateUtils.getNowDate();

        SysUser loginSysUser = (SysUser) authentication.getPrincipal();
        String wxOpenId = loginSysUser.getWxOpenId();
        Date loginDate = loginSysUser.getLoginDate();

        SysUser sysUser = sysUserMapper.selectUserByOpenId(wxOpenId);
        if (ObjectUtils.isEmpty(sysUser)) {
            log.debug("用户openid[" + wxOpenId + "]不存在");
            throw new RuntimeException("用户不存在");
        }

        if (!DateUtils.isSameInstant(loginDate, sysUser.getLoginDate())) {
            log.debug("token发行时间[" + loginDate + "],当前数据库登录时间[" + sysUser.getLoginDate() + "]");
            throw new RuntimeException("token过期");
        }

        UserContext userContext = new UserContext(sysUser);

        return new UsernamePasswordAuthenticationToken(userContext, null, new ArrayList<>());
    }

}
