package handler

import (
	"net/http"
	"nymdrop/internal/pow"
	"nymdrop/internal/relay"
)

type Submit struct {
	relay *relay.Relay
	pow   *pow.Verifier
}

func NewSubmit(r *relay.Relay, p *pow.Verifier) *Submit {
	return &Submit{relay: r, pow: p}
}

func (s *Submit) ServeHTTP(w http.ResponseWriter, r *http.Request) {
	if r.Method != http.MethodPost {
		http.Error(w, "method not allowed", http.StatusMethodNotAllowed)
		return
	}

	// Proof-of-work computed client-side (X-Nymdrop-Pow: "<unix-ts>:<nonce>").
	// Rejects unproven, expired, and replayed stamps before touching the relay.
	if err := s.pow.Verify(r.Header.Get("X-Nymdrop-Pow")); err != nil {
		// Generic error — don't reveal which check failed.
		http.Error(w, "error", http.StatusBadRequest)
		return
	}

	r.Body = http.MaxBytesReader(w, r.Body, 11*1024*1024) // wire size, see relay.maxPayloadBytes
	defer r.Body.Close()

	if err := s.relay.Forward(r.Body); err != nil {
		// Generic error — reveal nothing about internals.
		http.Error(w, "error", http.StatusInternalServerError)
		return
	}

	w.WriteHeader(http.StatusOK)
	w.Write([]byte("ok"))
}
