package com.fs.feishu.util;


import javax.crypto.Cipher;
import javax.crypto.spec.SecretKeySpec;
import java.nio.charset.StandardCharsets;
import java.util.Base64;
import java.util.HashMap;
import java.util.Map;


public class SecureTokenUtil {

    private static final String ALGORITHM = "AES";
    private static final String TRANSFORMATION = "AES/ECB/PKCS5Padding";
    private static final String SECRET_KEY = "9f3a7c21b8e4d6a5c2f1097e3b4a6d8f"; // 16字节密钥

    /**
     * 生成飞书看课课程访问 token（与 getNoAuthH5CourseVideoDetails 解析规则一致）。
     */
    public static String generateCourseAccessToken(Long companyUserId, Long videoId, Long userId) {
        long timestamp = System.currentTimeMillis() / 1000;
        long effectiveUserId = userId != null ? userId : 0L;
        return generateTokenUser(companyUserId, videoId, 0L, timestamp, effectiveUserId);
    }

    /**
     * 生成安全令牌
     */
    public static String generateToken(Long companyUserId, Long videoId,  Long timestamp) {
        try {
            String dataBuilder = companyUserId + ":" + videoId + ":" + timestamp;
            return encryptData(dataBuilder);
        } catch (Exception e) {
            throw new RuntimeException("飞书令牌生成失败", e);
        }
    }

    /**
     * 生成安全令牌
     */
    public static String generateTokenUser(Long companyUserId, Long videoId, Long periodId, Long timestamp,Long userId) {
        try {
            String dataBuilder = companyUserId + ":" + videoId + ":" + periodId + ":"+userId+":" + timestamp;
            return encryptData(dataBuilder);
        } catch (Exception e) {
            throw new RuntimeException("飞书令牌生成失败", e);
        }
    }

    /**
     * 加密数据
     */
    private static String encryptData(String data) throws Exception {
        SecretKeySpec keySpec = new SecretKeySpec(SECRET_KEY.getBytes(StandardCharsets.UTF_8), ALGORITHM);
        Cipher cipher = Cipher.getInstance(TRANSFORMATION);
        cipher.init(Cipher.ENCRYPT_MODE, keySpec);
        byte[] encrypted = cipher.doFinal(data.getBytes(StandardCharsets.UTF_8));
        return Base64.getUrlEncoder().withoutPadding().encodeToString(encrypted);
    }

    /**
     * 解析安全令牌（兼容4字段和5字段）
     */
    public static Map<String, Object> parseToken(String token) {
        try {
            String decryptedData = decryptData(token);
            String[] parts = decryptedData.split(":");

            Map<String, Object> result = new HashMap<>();
            result.put("companyUserId", Long.parseLong(parts[0]));
            result.put("videoId", Long.parseLong(parts[1]));
            result.put("periodId", Long.parseLong(parts[2]));
            if (parts.length == 5) {
                result.put("userId", Long.parseLong(parts[3]));
                result.put("timestamp", Long.parseLong(parts[4]));
            } else {
                result.put("timestamp", Long.parseLong(parts[3]));
            }

            return result;
        } catch (Exception e) {
            throw new RuntimeException("飞书令牌解析失败", e);
        }
    }

    /**
     * 解密数据
     */
    private static String decryptData(String encryptedData) throws Exception {
        SecretKeySpec keySpec = new SecretKeySpec(SECRET_KEY.getBytes(StandardCharsets.UTF_8), ALGORITHM);
        Cipher cipher = Cipher.getInstance(TRANSFORMATION);
        cipher.init(Cipher.DECRYPT_MODE, keySpec);
        byte[] decrypted = cipher.doFinal(Base64.getUrlDecoder().decode(encryptedData));
        return new String(decrypted, StandardCharsets.UTF_8);
    }

    /**
     * 验证令牌时效性
     */
    public static boolean isTokenValid(Long timestamp) {
        if (timestamp == null) {
            return false;
        }
        long currentTime = System.currentTimeMillis() / 1000;
        return (currentTime - timestamp) <= 60 * 60 * 24 * 2;
    }
}
