package com.ai.da.common.security.jwt;

import cn.hutool.core.map.MapUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.crypto.digest.DigestUtil;
import com.ai.da.common.constant.CommonConstant;
import com.ai.da.common.security.config.SecurityProperties;
import com.ai.da.model.vo.AuthPrincipalVo;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import io.jsonwebtoken.Claims;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.security.Keys;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import jakarta.annotation.Resource;
import javax.crypto.SecretKey;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.Date;

/**
 * @author: dangweijian
 * @description: JWT工具
 * @create: 2020-07-09 09:27
 **/
@Slf4j
@Component
public class JWTTokenHelper {

    @Resource
    private SecurityProperties securityProperties;

    private static final String ISSUER = "DWJ";
    private static final String AUTHORITIES = "authorities";
    private static final String CHANGE_MAILBOX = "changeMailbox";

    public String createToken(AuthPrincipalVo principal) {
        SecretKey key = buildSigningKey();
        String token = Jwts.builder()
                .id(String.valueOf(principal.getId()))
                .subject(JSONObject.toJSONString(principal))
                .issuedAt(new Date())
                .issuer(ISSUER)
                .claim(AUTHORITIES, JSON.toJSONString(new ArrayList<>()))//自定义属性  权限
                .expiration(new Date(System.currentTimeMillis() + securityProperties.getJwtExpiration()))
                .signWith(key)
                .compact();
        token = securityProperties.getJwtTokenPrefix() + token;
        return token;
    }

    public boolean validateToken(String token) {
        Claims claims = parser(token);
        if (MapUtil.isEmpty(claims)) {
            return false;
        }
        return true;
    }

    public AuthPrincipalVo parserToUser(String token) {
        String subject = parser(token).getSubject();
        if (StrUtil.isNotEmpty(subject)) {
            return JSONObject.parseObject(subject, AuthPrincipalVo.class);
        }
        return null;
    }

    public Claims parser(String token) {
        token = token.replaceAll(securityProperties.getJwtTokenPrefix(), "");
        SecretKey key = buildSigningKey();
        return Jwts.parser()
                .verifyWith(key)
                .build()
                .parseSignedClaims(token)
                .getPayload();
    }

    public String createToken(Long userId, String userEmail){
        SecretKey key = buildSigningKey();
        String token = Jwts.builder()
                .id(String.valueOf(userId))
                .subject(userEmail + "_" + userId)
                .issuedAt(new Date())
                .issuer(ISSUER)
                .claim(CHANGE_MAILBOX, JSON.toJSONString(new ArrayList<>()))//自定义属性  权限
                .expiration(new Date(System.currentTimeMillis() + CommonConstant.CHANGE_MAILBOX_LINK_VALIDITY))
                .signWith(key)
                .compact();
        return token;
    }

    public String parseToEmailAndId(String token) {
        return parser(token).getSubject();
    }

    /**
     * JWT 要求 HMAC-SHA 的密钥至少 256 bit，这里统一扩展/哈希密钥长度避免 WeakKeyException。
     */
    private SecretKey buildSigningKey() {
        byte[] raw = securityProperties.getJwtSecret().getBytes(StandardCharsets.UTF_8);
        if (raw.length < 32) {
            raw = DigestUtil.sha256(raw);
        }
        return Keys.hmacShaKeyFor(raw);
    }
}
