package quote_idempotency_service

import (
	"crypto/sha256"
	"encoding/hex"

	quotationv2 "github.com/tech/sendico/pkg/proto/payments/quotation/v2"
	"google.golang.org/protobuf/proto"
)

func (s *QuoteIdempotencyService) FingerprintQuotePayment(req *quotationv2.QuotePaymentRequest) string {
	if req == nil {
		return hashBytes([]byte("nil_request"))
	}

	cloned := proto.Clone(req).(*quotationv2.QuotePaymentRequest)
	cloned.Meta = nil
	cloned.IdempotencyKey = ""
	cloned.PreviewOnly = false

	return fingerprintMessage(cloned)
}

func (s *QuoteIdempotencyService) FingerprintQuotePayments(req *quotationv2.QuotePaymentsRequest) string {
	if req == nil {
		return hashBytes([]byte("nil_request"))
	}

	cloned := proto.Clone(req).(*quotationv2.QuotePaymentsRequest)
	cloned.Meta = nil
	cloned.IdempotencyKey = ""
	cloned.PreviewOnly = false

	return fingerprintMessage(cloned)
}

func fingerprintMessage(msg proto.Message) string {
	b, err := proto.MarshalOptions{Deterministic: true}.Marshal(msg)
	if err != nil {
		return hashBytes([]byte("marshal_error"))
	}
	return hashBytes(b)
}

func hashBytes(data []byte) string {
	sum := sha256.Sum256(data)
	return hex.EncodeToString(sum[:])
}
