package org.dromara.zhishu.service.impl;

import lombok.RequiredArgsConstructor;
import org.dromara.zhishu.service.SignGeneratorService;
import org.springframework.stereotype.Service;

import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;

@RequiredArgsConstructor
@Service
public class SignGeneratorServiceImpl implements SignGeneratorService {

    @Override
    public String generateCallbackSign(String loginCode, long timestamp, String secret) {
        try {
            // 签名算法：SHA256(loginCode + timestamp + secret)
            String signStr = loginCode + timestamp + secret;

            // 计算SHA256
            MessageDigest digest = MessageDigest.getInstance("SHA-256");
            byte[] hashed = digest.digest(signStr.getBytes());

            // 转换为十六进制字符串
            return bytesToHex(hashed);

        } catch (NoSuchAlgorithmException e) {
            throw new RuntimeException("SHA-256 algorithm not found", e);
        }
    }

    private static String bytesToHex(byte[] bytes) {
        StringBuilder hexString = new StringBuilder();
        for (byte b : bytes) {
            String hex = Integer.toHexString(0xff & b);
            if (hex.length() == 1) {
                hexString.append('0');
            }
            hexString.append(hex);
        }
        return hexString.toString();
    }
}