package com.sikey.wa04.common.utils;

import cn.hutool.core.convert.NumberWithFormat;
import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONObject;
import cn.hutool.jwt.JWT;
import cn.hutool.jwt.JWTUtil;
import lombok.Getter;

import java.io.Serial;
import java.io.Serializable;
import java.util.HashMap;
import java.util.Map;

/**
 * AccessToken工具类
 *
 * @author luoyangwei
 * @date 2024年10月09日10:06:37
 */
public class AccessTokenUtil {
    private static final byte[] key = "01926f123bd676608db755801227322f".getBytes();

    @Getter
    public static class AccessTokenBuilder implements Serializable {
        @Serial
        private static final long serialVersionUID = 1L;

        private String id;
        private Long expire;

        public AccessTokenBuilder setId(String id) {
            this.id = id;
            return this;
        }

        public AccessTokenBuilder setExpire(Long expire) {
            this.expire = expire;
            return this;
        }

        @Override
        public String toString() {
            return new JSONObject(this).toString();
        }
    }

    public static AccessTokenBuilder newBuilder() {
        return new AccessTokenBuilder();
    }

    public static String create(AccessTokenBuilder builder) {
        final Map<String, Object> tokenMap = new HashMap<>();
        tokenMap.put("uid", builder.id);
        tokenMap.put("exp", builder.expire);
        return JWTUtil.createToken(tokenMap, key);
    }

    public static AccessTokenBuilder parse(String accessToken) {
        accessToken = StrUtil.replace(accessToken, "Bearer ", "");
        final JWT jwt = JWTUtil.parseToken(accessToken);
        final AccessTokenBuilder builder = new AccessTokenBuilder();
        builder.setId((String) jwt.getPayload("uid"));
        builder.setExpire(((NumberWithFormat) jwt.getPayload("exp")).longValue());
        return builder;
    }
}
