package com.liquidnet.service.adam.support;

import com.liquidnet.common.cache.redis.util.RedisUtil;
import com.liquidnet.commons.lang.core.JwtValidator;
import com.liquidnet.commons.lang.util.CollectionUtil;
import com.liquidnet.commons.lang.util.CurrentUtil;
import com.liquidnet.commons.lang.util.DateUtil;
import com.liquidnet.service.adam.dto.vo.AdamUserInfoVo;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.Map;

/**
 * 用户 JTI 会话：adam:session:{jti}=uid，adam:session:user:{uid} 记录活跃 jti。
 */
@Component
public class AdamUserSessionSupport {

    @Autowired
    private RedisUtil redisUtil;
    @Autowired
    private JwtValidator jwtValidator;

    public void bindSession(String jti, String uid) {
        long sessionTtlSec = jwtValidator.getExpireTtl() * 60;
        redisUtil.set(jwtValidator.sessionKey(jti), uid, sessionTtlSec);
        redisUtil.sSetAndTime(jwtValidator.userSessionsKey(uid), sessionTtlSec, jti);
    }

    public void unbindSession(String jti, String uid) {
        if (StringUtils.isBlank(jti)) {
            return;
        }
        redisUtil.del(jwtValidator.sessionKey(jti));
        if (StringUtils.isNotBlank(uid)) {
            redisUtil.setRemove(jwtValidator.userSessionsKey(uid), jti);
        }
    }

    public String issueToken(AdamUserInfoVo userInfoVo) {
        Map<String, Object> claimsMap = CollectionUtil.mapStringObject();
        claimsMap.put(CurrentUtil.TOKEN_SUB, userInfoVo.getUid());
        claimsMap.put(CurrentUtil.TOKEN_MOBILE, userInfoVo.getMobile());
        claimsMap.put(CurrentUtil.TOKEN_NICKNAME, userInfoVo.getNickname());
        claimsMap.put(CurrentUtil.TOKEN_TYPE, CurrentUtil.TOKEN_TYPE_VAL_USER);
        claimsMap.put(CurrentUtil.TOKEN_UCREATED, DateUtil.Formatter.yyyyMMddHHmmssTrim.format(userInfoVo.getCreateAt()));
        String jti = jwtValidator.generateJti();
        String token = jwtValidator.create(claimsMap, jti);
        bindSession(jti, userInfoVo.getUid());
        return token;
    }
}
