package relay

import (
	"crypto/rand"
	"encoding/hex"
	"fmt"
	"io"
	"nymdrop/internal/nym"
)

// One base64 layer remains between the raw file and the wire: the browser
// client base64-encodes the file into the plaintext before encrypting (see
// static/crypto.js, ~4/3 inflation). nym.Client.Send used to base64-encode
// the whole ciphertext a second time to embed it in a JSON message for the
// local nym-client's WebSocket control channel; it now sends the raw bytes
// via nym-client's binary protocol instead, so that second inflation is
// gone. The remaining ~4/3 inflation is still bounded above by nym-client's
// own hardcoded 16MB WebSocket message limit. This cap (11MB) predates the
// binary-protocol fix and still reflects the old two-layer math (safe raw
// file size ~8MB) — raising it towards the ~16MB/1.33 headroom the fix
// actually unlocked is a deliberate follow-up, not done here.
const maxPayloadBytes = 11 * 1024 * 1024 // 11 MB wire

// Relay receives ciphertext and forwards it through Nym. Nothing is written to disk.
type Relay struct {
	nym *nym.Client
}

func New(client *nym.Client) *Relay {
	return &Relay{nym: client}
}

// Forward reads ciphertext from r, sends it over Nym, then zeros the buffer.
func (r *Relay) Forward(body io.Reader) error {
	buf := make([]byte, maxPayloadBytes)
	n, err := io.ReadFull(body, buf)
	if err != nil && err != io.ErrUnexpectedEOF {
		return fmt.Errorf("read payload: %w", err)
	}
	payload := buf[:n]
	defer zeroBytes(payload)

	// Prepend a random nonce so identical submissions look different on the wire.
	nonce := make([]byte, 16)
	if _, err := rand.Read(nonce); err != nil {
		return fmt.Errorf("nonce: %w", err)
	}
	packet := append([]byte(hex.EncodeToString(nonce)+":"), payload...)
	defer zeroBytes(packet)

	return r.nym.Send(packet)
}

func zeroBytes(b []byte) {
	for i := range b {
		b[i] = 0
	}
}
