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.util.HexFormat;

public final class VehicleKey {

    private VehicleKey() {
    }

    public static String derive(ProtocolId protocol, String vin, String phone, String rawIdentitySeed) {
        if (protocol == null) {
            throw new IllegalArgumentException("protocol must not be null");
        }
        String normalizedVin = clean(vin);
        if (!normalizedVin.isBlank()) {
            return normalizedVin;
        }
        String normalizedPhone = clean(phone);
        if (protocol == ProtocolId.JT808 && !normalizedPhone.isBlank()) {
            return "jt808:" + normalizedPhone;
        }
        String seed = clean(rawIdentitySeed);
        if (seed.isBlank()) {
            seed = protocol.name();
        }
        return "unknown:" + protocol.name() + ":" + sha256(seed).substring(0, 16);
    }

    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);
        }
    }
}
