package orchestrator

import (
	"context"
	"testing"
	"time"

	oracleclient "github.com/tech/sendico/fx/oracle/client"
	fxv1 "github.com/tech/sendico/pkg/proto/common/fx/v1"
	moneyv1 "github.com/tech/sendico/pkg/proto/common/money/v1"
	orchestratorv1 "github.com/tech/sendico/pkg/proto/payments/orchestrator/v1"
	"go.uber.org/zap"
)

func TestRequestFXQuoteUsesQuoteAmountWhenCurrencyMatchesQuote(t *testing.T) {
	ctx := context.Background()
	var captured oracleclient.GetQuoteParams

	svc := &Service{
		logger: zap.NewNop(),
		clock:  testClock{now: time.Now()},
		deps: serviceDependencies{
			oracle: oracleDependency{
				client: &oracleclient.Fake{
					GetQuoteFn: func(ctx context.Context, params oracleclient.GetQuoteParams) (*oracleclient.Quote, error) {
						captured = params
						return &oracleclient.Quote{
							QuoteRef:    "q",
							Pair:        params.Pair,
							Side:        params.Side,
							Price:       "1.1",
							BaseAmount:  params.BaseAmount,
							QuoteAmount: params.QuoteAmount,
							ExpiresAt:   time.Now(),
						}, nil
					},
				},
			},
		},
	}

	req := &orchestratorv1.QuotePaymentRequest{
		Meta: &orchestratorv1.RequestMeta{OrganizationRef: "org"},
		Intent: &orchestratorv1.PaymentIntent{
			Amount:             &moneyv1.Money{Currency: "USD", Amount: "100"},
			SettlementCurrency: "USD",
			Fx: &orchestratorv1.FXIntent{
				Pair: &fxv1.CurrencyPair{Base: "EUR", Quote: "USD"},
				Side: fxv1.Side_BUY_BASE_SELL_QUOTE,
			},
		},
	}

	if _, err := svc.requestFXQuote(ctx, "org", req); err != nil {
		t.Fatalf("requestFXQuote returned error: %v", err)
	}

	if captured.QuoteAmount == nil {
		t.Fatal("expected quote amount to be populated")
	}
	if captured.BaseAmount != nil {
		t.Fatal("expected base amount to be nil when using quote amount input")
	}
	if captured.QuoteAmount.GetCurrency() != "USD" {
		t.Fatalf("expected quote amount currency USD, got %s", captured.QuoteAmount.GetCurrency())
	}
}
