package payments

import (
	"context"
	"fmt"
	"time"

	"github.com/saveinmed/backend-go/internal/domain"
)

// MercadoPagoGateway fakes the split configuration while keeping the API contract ready for the SDK.
type MercadoPagoGateway struct {
	MarketplaceCommission float64
	BaseURL               string
}

func NewMercadoPagoGateway(baseURL string, commission float64) *MercadoPagoGateway {
	return &MercadoPagoGateway{
		MarketplaceCommission: commission,
		BaseURL:               baseURL,
	}
}

func (g *MercadoPagoGateway) CreatePreference(ctx context.Context, order *domain.Order) (*domain.PaymentPreference, error) {
	select {
	case <-ctx.Done():
		return nil, ctx.Err()
	default:
	}

	fee := int64(float64(order.TotalCents) * (g.MarketplaceCommission / 100))
	pref := &domain.PaymentPreference{
		OrderID:          order.ID,
		Gateway:          "mercadopago",
		CommissionPct:    g.MarketplaceCommission,
		MarketplaceFee:   fee,
		SellerReceivable: order.TotalCents - fee,
		PaymentURL:       fmt.Sprintf("%s/checkout/v1/redirect?order_id=%s", g.BaseURL, order.ID.String()),
	}

	// In a real gateway this is where the SDK call would run; we preserve latency budgets.
	time.Sleep(10 * time.Millisecond)
	return pref, nil
}
