package orchestrator

import (
	"context"
	"testing"

	paymodel "github.com/tech/sendico/payments/orchestrator/storage/model"
	mloggerfactory "github.com/tech/sendico/pkg/mlogger/factory"
	"github.com/tech/sendico/pkg/model"
)

func TestGatewayExecutionConfirmedUpdatesPayment(t *testing.T) {
	logger := mloggerfactory.NewLogger(false)
	store := newHelperPaymentStore()
	payment := &paymodel.Payment{PaymentRef: "pi-1", State: paymodel.PaymentStateSubmitted}
	if err := store.Create(context.Background(), payment); err != nil {
		t.Fatalf("failed to seed payment: %v", err)
	}
	svc := &Service{
		logger:  logger,
		storage: stubRepo{payments: store},
	}
	exec := &model.PaymentGatewayExecution{
		PaymentIntentID: "pi-1",
		Status:          model.ConfirmationStatusConfirmed,
		RequestID:       "req-1",
		QuoteRef:        "quote-1",
	}
	if err := svc.onGatewayExecution(context.Background(), exec); err != nil {
		t.Fatalf("onGatewayExecution error: %v", err)
	}
	updated, _ := store.GetByPaymentRef(context.Background(), "pi-1")
	if updated.State != paymodel.PaymentStateSettled {
		t.Fatalf("expected payment settled, got %s", updated.State)
	}
	if updated.Metadata["gateway_request_id"] != "req-1" {
		t.Fatalf("expected gateway_request_id metadata")
	}
	if updated.Metadata["gateway_confirmation_status"] != string(model.ConfirmationStatusConfirmed) {
		t.Fatalf("expected gateway_confirmation_status metadata")
	}
}

func TestGatewayExecutionRejectedFailsPayment(t *testing.T) {
	logger := mloggerfactory.NewLogger(false)
	store := newHelperPaymentStore()
	payment := &paymodel.Payment{PaymentRef: "pi-2", State: paymodel.PaymentStateSubmitted}
	if err := store.Create(context.Background(), payment); err != nil {
		t.Fatalf("failed to seed payment: %v", err)
	}
	svc := &Service{
		logger:  logger,
		storage: stubRepo{payments: store},
	}
	exec := &model.PaymentGatewayExecution{
		PaymentIntentID: "pi-2",
		Status:          model.ConfirmationStatusRejected,
	}
	if err := svc.onGatewayExecution(context.Background(), exec); err != nil {
		t.Fatalf("onGatewayExecution error: %v", err)
	}
	updated, _ := store.GetByPaymentRef(context.Background(), "pi-2")
	if updated.State != paymodel.PaymentStateFailed {
		t.Fatalf("expected payment failed, got %s", updated.State)
	}
	if updated.FailureReason != "gateway_rejected" {
		t.Fatalf("expected failure reason gateway_rejected, got %q", updated.FailureReason)
	}
}
