package de.winniepat.citrus.utils;

import de.winniepat.citrus.Client;

import javax.crypto.Mac;
import javax.crypto.spec.SecretKeySpec;
import java.nio.charset.StandardCharsets;
import java.time.ZoneOffset;

public class SecurityUtils {
    private static final String MASTER_SECRET = "xhIc7PAz0whLGm8t8EsIK574mDqvuqGs6oWLm0pWynkSnpuTU14iML1FDHdlXOJhHQBww65mcehps0fYBUnVJe5m4GR7HHlnBjQxQQ4crqhw4R3AbegwByr7aEg6XvwP";

    public static String getDailyKey() {
        try {
            String date = java.time.LocalDate.now(ZoneOffset.UTC).toString();

            SecretKeySpec signingKey = new SecretKeySpec(
                    MASTER_SECRET.getBytes(StandardCharsets.UTF_8), "HmacSHA256"
            );
            Mac mac = Mac.getInstance("HmacSHA256");
            mac.init(signingKey);

            byte[] rawHmac = mac.doFinal(date.getBytes(StandardCharsets.UTF_8));
            return bytesToHex(rawHmac);
        } catch (Exception e) {
            Client.logger.error("Error while getting daily key", e);
            return "";
        }
    }

    private static String bytesToHex(byte[] bytes) {
        StringBuilder sb = new StringBuilder();
        for (byte b : bytes) {
            sb.append(String.format("%02x", b));
        }
        return sb.toString();
    }
}
