package com.lingniu.ingest.facts;

import com.lingniu.ingest.api.ProtocolId;

import java.nio.charset.StandardCharsets;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.time.Instant;
import java.util.HexFormat;

public final class FactIds {

    private FactIds() {
    }

    public static String rawFrameId(ProtocolId protocol,
                                    String vehicleKey,
                                    int messageId,
                                    int subType,
                                    Instant receivedAt,
                                    String checksum) {
        if (protocol == null) {
            throw new IllegalArgumentException("protocol must not be null");
        }
        String input = protocol.name() + "|"
                + clean(vehicleKey) + "|"
                + messageId + "|"
                + subType + "|"
                + (receivedAt == null ? "" : receivedAt.toString()) + "|"
                + clean(checksum);
        return "rf_" + sha256(input).substring(0, 32);
    }

    public static String decodedFactId(String frameId, String kind, int ordinal) {
        return "df_" + clean(frameId) + "_" + clean(kind) + "_" + ordinal;
    }

    private static String clean(String value) {
        return value == null ? "" : value.trim();
    }

    private static String sha256(String value) {
        try {
            MessageDigest digest = MessageDigest.getInstance("SHA-256");
            return HexFormat.of().formatHex(digest.digest(value.getBytes(StandardCharsets.UTF_8)));
        } catch (NoSuchAlgorithmException e) {
            throw new IllegalStateException("SHA-256 is unavailable", e);
        }
    }
}
