package orchestrator

import (
	"context"
	"strings"
	"testing"

	ledgerclient "github.com/tech/sendico/ledger/client"
	"github.com/tech/sendico/payments/orchestrator/storage/model"
	mo "github.com/tech/sendico/pkg/model"
	paymenttypes "github.com/tech/sendico/pkg/payments/types"
	"go.mongodb.org/mongo-driver/v2/bson"
	"go.uber.org/zap"
)

func TestReleasePaymentHold_RejectsLegacyLedgerRelease(t *testing.T) {
	ctx := context.Background()

	store := newStubPaymentsStore()
	repo := &stubRepository{store: store}

	ledgerFake := &ledgerclient.Fake{}

	svc := &Service{
		logger:  zap.NewNop(),
		storage: repo,
		deps: serviceDependencies{
			ledger: ledgerDependency{
				client:   ledgerFake,
				internal: ledgerFake,
			},
		},
	}

	executor := newPaymentExecutor(&svc.deps, svc.logger, svc)

	payment := &model.Payment{
		PaymentRef:     "pay-release-1",
		IdempotencyKey: "pay-release-1",
		OrganizationBoundBase: mo.OrganizationBoundBase{
			OrganizationRef: bson.NewObjectID(),
		},
		Intent: model.PaymentIntent{
			Ref:  "ref-release-1",
			Kind: model.PaymentKindPayout,
			Source: model.PaymentEndpoint{
				Type: model.EndpointTypeManagedWallet,
				ManagedWallet: &model.ManagedWalletEndpoint{
					ManagedWalletRef: "wallet-src",
				},
			},
			Attributes: map[string]string{
				"ledger_debit_account_ref": "ledger:debit",
				"ledger_block_account_ref": "ledger:block",
			},
		},
		PaymentPlan: &model.PaymentPlan{
			ID:             "pay-release-1",
			IdempotencyKey: "pay-release-1",
			Steps: []*model.PaymentStep{
				{StepID: "ledger_block", Rail: model.RailLedger, Action: model.RailOperationBlock, Amount: &paymenttypes.Money{Currency: "USD", Amount: "100"}},
				{StepID: "ledger_release", Rail: model.RailLedger, Action: model.RailOperationRelease, DependsOn: []string{"ledger_block"}, Amount: &paymenttypes.Money{Currency: "USD", Amount: "100"}},
			},
		},
	}

	store.payments[payment.PaymentRef] = payment

	execPlan := ensureExecutionPlanForPlan(payment, payment.PaymentPlan)
	steps := executionStepsByCode(execPlan)
	blockStep := steps["ledger_block"]
	if blockStep == nil {
		t.Fatalf("expected block step in execution plan")
	}
	setExecutionStepStatus(blockStep, model.OperationStateSuccess)

	err := executor.releasePaymentHold(ctx, store, payment)
	if err == nil {
		t.Fatal("expected legacy ledger operation error")
	}
	if !strings.Contains(err.Error(), "unsupported action") {
		t.Fatalf("unexpected error: %v", err)
	}
}
