package com.hc.business.model.jwt;

import com.hc.business.model.UserAdmin;
import com.hc.business.model.User;
import com.hc.business.model.login.AccessEntity;
import com.hc.business.model.login.AuthEntity;
import com.hc.business.model.login.TokenEntity;
import com.hc.core.utils.exception.ResponseException;
import com.hc.core.utils.redis.RedisUtil;
import com.hc.core.utils.tool.IdGenerator;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import org.springframework.util.SerializationUtils;

import java.util.Objects;

@Slf4j
@Component
public class GenerateAuthToken {


    private final RedisUtil redisUtil;

    public GenerateAuthToken(RedisUtil redisUtil) {
        this.redisUtil = redisUtil;
    }

    public AccessEntity generateToken(AuthEntity auth, User user, UserAdmin userAdmin) {

        AccessEntity accessEntity = new AccessEntity();
        accessEntity.setAuth(auth);
        TokenEntity tokenEntity = new TokenEntity();
        // 默认超时 8 小时
        tokenEntity.setExpires(60 * 60 * 24 * 7);
        String token = JWTUtil.sign(auth.getUserName(), IdGenerator.passwordToHash(auth.getPassword()));
        tokenEntity.setId(token);

        if (userAdmin != null) {
            //设置权限级别
            tokenEntity.setPermissionLevel(userAdmin.getPermissionLevel());
        }

        accessEntity.setToken(tokenEntity);

        String accessEntityStr = null;
        try {
            accessEntityStr = new String(Objects.requireNonNull(SerializationUtils.serialize(accessEntity)));
        } catch (Exception e) {
            throw new ResponseException(-1,"登录序列化失败");
        }

        // 写入到 redis
        redisUtil.set(accessEntity.getToken().getId(),
                accessEntityStr,
                accessEntity.getToken().getExpires());

        if (user != null) {
            accessEntity.setUser(user);
        }
        if (userAdmin != null){
            accessEntity.setUserAdmin(userAdmin);
        }
        log.info("user: {}", auth.getUserName()+" 成功登录系统");
        return accessEntity;
    }
}
