package orchestrator

import (
	"testing"

	"github.com/tech/sendico/payments/orchestrator/internal/service/orchestrationv2/agg"
	"github.com/tech/sendico/payments/orchestrator/internal/service/orchestrationv2/xplan"
	"github.com/tech/sendico/payments/storage/model"
	paymenttypes "github.com/tech/sendico/pkg/payments/types"
)

func TestDestinationOperationComment_AssignsCommentByDestinationHopRole(t *testing.T) {
	comment := destinationOperationComment(
		&agg.Payment{IntentSnapshot: model.PaymentIntent{Comment: "  invoice-7  "}},
		xplan.Step{HopRole: paymenttypes.QuoteRouteHopRoleDestination},
	)

	if got, want := comment, "invoice-7"; got != want {
		t.Fatalf("comment mismatch: got=%q want=%q", got, want)
	}
}

func TestDestinationOperationComment_DoesNotAssignForNonDestinationHop(t *testing.T) {
	comment := destinationOperationComment(
		&agg.Payment{IntentSnapshot: model.PaymentIntent{Comment: "invoice-7"}},
		xplan.Step{HopRole: paymenttypes.QuoteRouteHopRoleSource},
	)

	if comment != "" {
		t.Fatalf("comment must not be set for non-destination hop")
	}
}

func TestDestinationOperationComment_PrefersPerTargetComment(t *testing.T) {
	comment := destinationOperationComment(
		&agg.Payment{IntentSnapshot: model.PaymentIntent{Comment: "payment-comment"}},
		xplan.Step{
			HopRole: paymenttypes.QuoteRouteHopRoleDestination,
			Comment: "  recipient-comment  ",
		},
	)

	if got, want := comment, "recipient-comment"; got != want {
		t.Fatalf("comment mismatch: got=%q want=%q", got, want)
	}
}

func TestAssignDestinationStepComment_AssignsForDestinationHop(t *testing.T) {
	stepExecution := agg.StepExecution{}
	assignDestinationStepComment(
		&stepExecution,
		&agg.Payment{IntentSnapshot: model.PaymentIntent{Comment: "  invoice-8 "}},
		xplan.Step{
			StepRef:  "hop_4",
			StepCode: "hop.4.card.send",
			HopRole:  paymenttypes.QuoteRouteHopRoleDestination,
		},
	)

	if got, want := stepExecution.Comment, "invoice-8"; got != want {
		t.Fatalf("step comment mismatch: got=%q want=%q", got, want)
	}
}

func TestAssignDestinationStepComment_ClearsForNonDestinationHop(t *testing.T) {
	stepExecution := agg.StepExecution{Comment: "old-value"}
	assignDestinationStepComment(
		&stepExecution,
		&agg.Payment{IntentSnapshot: model.PaymentIntent{Comment: "invoice-8"}},
		xplan.Step{
			StepRef:  "hop_1",
			StepCode: "hop.1.crypto.send",
			HopRole:  paymenttypes.QuoteRouteHopRoleSource,
		},
	)

	if got := stepExecution.Comment; got != "" {
		t.Fatalf("step comment must be empty for non-destination hop, got=%q", got)
	}
}
