package relay

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

// Two base64 layers stack between the raw file and the wire: the client
// base64-encodes the file into the plaintext before encrypting (see
// static/crypto.js, ~4/3 inflation), then nym.Client.Send base64-encodes
// the whole ciphertext again to embed it in the JSON message sent to the
// local nym-client over its control WebSocket (~4/3 again). The combined
// ~1.78x inflation is bounded above by nym-client's own hardcoded 16MB
// WebSocket message limit, not by anything in this codebase, so this
// buffer (and the nginx/http-layer cap) must stay well under 16MB / 1.78
// once the second layer is applied. 11MB here keeps the second-layer
// base64 (~14.7MB) with real margin below the 16MB nym-client ceiling,
// which works out to a safe raw file size of roughly 8MB, not 10MB.
const maxPayloadBytes = 11 * 1024 * 1024 // 11 MB wire (first base64 layer only)

// 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
	}
}
