package com.sonic.cow.client.rtc;

import com.google.common.collect.Lists;

import java.math.BigInteger;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.Collections;
import java.util.List;

/**
 * @description: 回调验签
 * @author: mzc
 * @date: 2025-08-04 15:00
 **/
public class CheckSignature {

    public static void main(String[] args) {
        Event event = new Event();
        event.EventType = "RoomCreate";
        event.EventData = "{\"RoomId\":\"room1\",\"Timestamp\":1679383924691}";
        event.EventTime = "2023-03-21T15:32:04+08:00";
        event.EventId = "123456";
        event.Version = "2020-12-01";
        event.AppId = "appId";
        event.Nonce = "aaBc";
        event.Signature = "1c7200723842eff514b65fc3f065597432bbb4249e10d33db79b3853d05f3691";
        String secretKey = "1234";

        boolean ret = check(event, secretKey);
        System.out.println(ret);

    }

    public static boolean check(Event event, String secretKey) {
        try {
            List<String> data = Lists.newArrayList();
            data.add(event.EventType);
            data.add(event.EventData);
            data.add(event.EventTime);
            data.add(event.EventId);
            data.add(event.AppId);
            data.add(event.Version);
            data.add(event.Nonce);
            data.add(secretKey);

            Collections.sort(data);

            final String payloadData = String.join("", data);
            MessageDigest digest = MessageDigest.getInstance("SHA-256");
            digest.update(payloadData.getBytes());
            String signature = byteToHexString(digest.digest());
            System.out.println(signature);

            if (event.Signature.equals(signature)) {
                return true;
            }
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
        }
        return false;
    }

    private static String byteToHexString(byte[] bytes) {
        return String.format("%064x", new BigInteger(1, bytes));
    }

}
