package api

import (
	"encoding/json"
	"log"
	"net/http"
	"dejo_node/internal/transactions"
)

func (h *Handler) SendTransaction(w http.ResponseWriter, r *http.Request) {
	log.Println("📥 Nova transação recebida")
	var tx transactions.Transaction
	decoder := json.NewDecoder(r.Body)
	if err := decoder.Decode(&tx); err != nil {
		http.Error(w, "formato inválido", http.StatusBadRequest)
		return
	}

	if tx.From == "" || tx.To == "" || tx.Value <= 0 {
		http.Error(w, "transação inválida", http.StatusBadRequest)
		return
	}

	h.Mempool.Add(&tx)
	log.Printf("✅ Transação adicionada ao mempool: %+v\n", tx)

	w.Header().Set("Content-Type", "application/json")
	w.WriteHeader(http.StatusOK)
	json.NewEncoder(w).Encode(map[string]string{"status": "ok"})
}