package me.proxylink.common;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.util.Objects;

public record StreamOpenPayload(String routeName) {
    public StreamOpenPayload {
        Objects.requireNonNull(routeName, "routeName");
        if (routeName.isBlank()) {
            throw new IllegalArgumentException("routeName must not be blank");
        }
    }

    public byte[] encode() throws IOException {
        ByteArrayOutputStream bytes = new ByteArrayOutputStream();
        DataOutputStream output = new DataOutputStream(bytes);
        output.writeUTF(routeName);
        output.flush();
        return bytes.toByteArray();
    }

    public static StreamOpenPayload decode(byte[] payload) throws IOException {
        DataInputStream input = new DataInputStream(new ByteArrayInputStream(payload));
        String routeName = input.readUTF();
        if (input.available() != 0) {
            throw new ProtocolException("Invalid STREAM_OPEN payload");
        }
        return new StreamOpenPayload(routeName);
    }
}
