package com.liquidnet.common.third.secureaccess.model;

import lombok.Builder;
import lombok.Getter;
import org.apache.commons.codec.binary.Hex;

/**
 * PID（认证服务凭据）按表 6 解码后的结构。
 */
@Getter
@Builder
public class NiaPidParsed {

    private static final int TIMESTAMP_LEN = 14;

    private final int totalLen;
    private final int version;
    /** 第 1–40 字节：网络身份应用标识（二进制，非文本） */
    private final byte[] identifier;
    /** 第 41–54 字节：yyyymmddhhmmss */
    private final String timestamp;
    /** 第 55+ 字节：签名 */
    private final byte[] signature;

    public String identifierHex() {
        return identifier == null ? null : Hex.encodeHexString(identifier).toUpperCase();
    }

    /** 标识段可视化：可打印字符原样，不可打印用 '.' */
    public String identifierVisual() {
        if (identifier == null) {
            return null;
        }
        StringBuilder sb = new StringBuilder(identifier.length);
        for (byte b : identifier) {
            sb.append(b >= 32 && b < 127 ? (char) b : '.');
        }
        return sb.toString();
    }

    public String signatureHexPrefix(int maxBytes) {
        if (signature == null || signature.length == 0) {
            return null;
        }
        int len = Math.min(signature.length, maxBytes);
        byte[] head = new byte[len];
        System.arraycopy(signature, 0, head, 0, len);
        String hex = Hex.encodeHexString(head);
        return signature.length > maxBytes ? hex + "..." : hex;
    }
}
