package l7

import "net"

// PrefixConn wraps a net.Conn, prepending buffered bytes before reading
// from the underlying connection. This is used to replay the TLS ClientHello
// bytes that were peeked during SNI extraction back into crypto/tls.Server.
type PrefixConn struct {
	net.Conn
	prefix []byte
	off    int
}

// NewPrefixConn creates a PrefixConn that returns prefix bytes first,
// then reads from the underlying conn.
func NewPrefixConn(conn net.Conn, prefix []byte) *PrefixConn {
	return &PrefixConn{Conn: conn, prefix: prefix}
}

// Read returns buffered prefix bytes first, then reads from the underlying conn.
func (pc *PrefixConn) Read(b []byte) (int, error) {
	if pc.off < len(pc.prefix) {
		n := copy(b, pc.prefix[pc.off:])
		pc.off += n
		return n, nil
	}
	return pc.Conn.Read(b)
}
