package cn.lihongjie.coal.common;

import lombok.experimental.UtilityClass;
import lombok.extern.slf4j.Slf4j;

import org.apache.commons.codec.digest.HmacAlgorithms;
import org.apache.commons.codec.digest.HmacUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.amqp.core.Message;

import java.nio.charset.StandardCharsets;
import java.util.*;
import java.util.function.Function;

@UtilityClass
@Slf4j
public class MessageSignUtils {

    public static boolean isValid(Message message, Function<String, String> appSecretProvider) {

        var body = new String(message.getBody(), StandardCharsets.UTF_8);

        Map<String, Object> headers = message.getMessageProperties().getHeaders();

        Object key = headers.get("appKey");

        if (key == null || StringUtils.isEmpty(key.toString())) {
            log.error("appKey is null");
            return false;
        }
        String appSecret;

        try {

            appSecret = appSecretProvider.apply(key.toString());
        } catch (Exception e) {
            log.error("appSecretProvider error", e);
            return false;
        }

        if (StringUtils.isEmpty(appSecret)) {

            log.error("appSecret is null");
            return false;
        }

        var sign =
                new HmacUtils(HmacAlgorithms.HMAC_SHA_256, appSecret)
                        .hmacHex(body.getBytes(StandardCharsets.UTF_8));

        if (!StringUtils.equals(sign, headers.get("sign").toString())) {
            log.error("sign not match {} {}", sign, headers.get("sign"));
            return false;
        }

        return true;
    }
}
