package quotation

import (
	"testing"

	"github.com/tech/sendico/payments/storage/model"
	paymenttypes "github.com/tech/sendico/pkg/payments/types"
	fxv1 "github.com/tech/sendico/pkg/proto/common/fx/v1"
	moneyv1 "github.com/tech/sendico/pkg/proto/common/money/v1"
	sharedv1 "github.com/tech/sendico/pkg/proto/payments/shared/v1"
)

func TestIntentFromProto_DerivesCanonicalFXFieldsAndFeeTreatment(t *testing.T) {
	src := &sharedv1.PaymentIntent{
		Amount:             &moneyv1.Money{Amount: "10", Currency: "USDT"},
		SettlementCurrency: "USD",
		RequiresFx:         false,
		Fx: &sharedv1.FXIntent{
			Pair: &fxv1.CurrencyPair{Base: "USDT", Quote: "RUB"},
			Side: fxv1.Side_SELL_BASE_BUY_QUOTE,
		},
		Attributes: map[string]string{
			"comment":         "invoice-7",
			"fee_treatment":   "deduct_from_destination",
			"settlement_mode": "fix_source",
		},
	}

	got := intentFromProto(src)
	if got.SettlementCurrency != "RUB" {
		t.Fatalf("unexpected settlement currency: got=%q", got.SettlementCurrency)
	}
	if !got.RequiresFX {
		t.Fatalf("expected requires_fx to be derived as true")
	}
	if got.FeeTreatment != model.FeeTreatmentDeductFromDestination {
		t.Fatalf("unexpected fee treatment: got=%q", got.FeeTreatment)
	}
	if _, ok := got.Attributes["fee_treatment"]; ok {
		t.Fatalf("fee_treatment must not be kept in generic attributes")
	}
	if _, ok := got.Attributes["settlement_mode"]; ok {
		t.Fatalf("settlement_mode must not be kept in generic attributes")
	}
	if got.Attributes["comment"] != "invoice-7" {
		t.Fatalf("comment attribute must be preserved")
	}
}

func TestProtoIntentFromModel_DerivesRequiresFXAndSettlementCurrency(t *testing.T) {
	src := model.PaymentIntent{
		Amount: &paymenttypes.Money{
			Amount:   "10",
			Currency: "USDT",
		},
		FX: &model.FXIntent{
			Pair: &paymenttypes.CurrencyPair{
				Base:  "USDT",
				Quote: "RUB",
			},
			Side: paymenttypes.FXSideSellBaseBuyQuote,
		},
		FeeTreatment: model.FeeTreatmentAddToSource,
		Attributes: map[string]string{
			"comment": "invoice-7",
		},
	}

	got := protoIntentFromModel(src)
	if got.GetSettlementCurrency() != "RUB" {
		t.Fatalf("unexpected settlement currency: got=%q", got.GetSettlementCurrency())
	}
	if !got.GetRequiresFx() {
		t.Fatalf("expected requires_fx=true to be derived from FX intent")
	}
	if got.GetAttributes()["fee_treatment"] != "add_to_source" {
		t.Fatalf("expected fee_treatment compatibility attribute to be set")
	}
	if got.GetAttributes()["comment"] != "invoice-7" {
		t.Fatalf("expected comment attribute to be preserved")
	}
}

func TestProtoIntentFromModel_DerivesRequiresFXFromCurrencyMismatchWithoutFX(t *testing.T) {
	src := model.PaymentIntent{
		Amount: &paymenttypes.Money{
			Amount:   "10",
			Currency: "USDT",
		},
		SettlementCurrency: "RUB",
	}

	got := protoIntentFromModel(src)
	if !got.GetRequiresFx() {
		t.Fatalf("expected requires_fx=true for currency mismatch")
	}
}
