package com.ruoyi.web.modules.screen.mallstats;

import java.nio.charset.StandardCharsets;
import java.util.Base64;
import java.util.UUID;
import javax.crypto.Cipher;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.SecretKeySpec;
import org.springframework.stereotype.Component;
import com.ruoyi.common.utils.StringUtils;

/**
 * 生成商城 Open Stats 请求头 {@code X-Open-Token}（AES-128-CBC 加密 UUID）。
 */
@Component
public class MallStatsOpenTokenSupport
{
    public static final String TOKEN_HEADER = "X-Open-Token";

    private static final String AES_TRANSFORMATION = "AES/CBC/PKCS5Padding";

    public String createToken(MallStatsOpenProperties properties)
    {
        String uuid = UUID.randomUUID().toString();
        return encrypt(uuid, properties.getAesKey(), properties.getAesIv());
    }

    static String encrypt(String plainText, String key, String iv)
    {
        if (StringUtils.isEmpty(plainText) || StringUtils.isEmpty(key) || StringUtils.isEmpty(iv))
        {
            throw new IllegalArgumentException("token plain/key/iv required");
        }
        try
        {
            Cipher cipher = Cipher.getInstance(AES_TRANSFORMATION);
            SecretKeySpec keySpec = new SecretKeySpec(key.getBytes(StandardCharsets.UTF_8), "AES");
            IvParameterSpec ivSpec = new IvParameterSpec(iv.getBytes(StandardCharsets.UTF_8));
            cipher.init(Cipher.ENCRYPT_MODE, keySpec, ivSpec);
            byte[] cipherBytes = cipher.doFinal(plainText.getBytes(StandardCharsets.UTF_8));
            return Base64.getEncoder().encodeToString(cipherBytes);
        }
        catch (Exception ex)
        {
            throw new IllegalStateException("生成商城 Open Token 失败", ex);
        }
    }
}
