package gateway

import (
	"strings"

	"github.com/tech/sendico/gateway/mntx/internal/service/monetix"
	"github.com/tech/sendico/pkg/merrors"
	mntxv1 "github.com/tech/sendico/pkg/proto/gateway/mntx/v1"
)

func validateCardTokenPayoutRequest(req *mntxv1.CardTokenPayoutRequest, cfg monetix.Config) error {
	if req == nil {
		return newPayoutError("invalid_request", merrors.InvalidArgument("request cannot be empty"))
	}

	if err := validateOperationIdentity(strings.TrimSpace(req.GetPayoutId()), strings.TrimSpace(req.GetOperationRef())); err != nil {
		return err
	}
	if strings.TrimSpace(req.GetParentPaymentRef()) == "" {
		return newPayoutError("missing_parent_payment_ref", merrors.InvalidArgument("parent_payment_ref is required", "parent_payment_ref"))
	}
	if strings.TrimSpace(req.GetCustomerId()) == "" {
		return newPayoutError("missing_customer_id", merrors.InvalidArgument("customer_id is required", "customer_id"))
	}
	if strings.TrimSpace(req.GetCustomerFirstName()) == "" {
		return newPayoutError("missing_customer_first_name", merrors.InvalidArgument("customer_first_name is required", "customer_first_name"))
	}
	if strings.TrimSpace(req.GetCustomerLastName()) == "" {
		return newPayoutError("missing_customer_last_name", merrors.InvalidArgument("customer_last_name is required", "customer_last_name"))
	}
	if strings.TrimSpace(req.GetCustomerIp()) == "" {
		return newPayoutError("missing_customer_ip", merrors.InvalidArgument("customer_ip is required", "customer_ip"))
	}
	if req.GetAmountMinor() <= 0 {
		return newPayoutError("invalid_amount", merrors.InvalidArgument("amount_minor must be positive", "amount_minor"))
	}

	currency := strings.ToUpper(strings.TrimSpace(req.GetCurrency()))
	if currency == "" {
		return newPayoutError("missing_currency", merrors.InvalidArgument("currency is required", "currency"))
	}
	if !cfg.CurrencyAllowed(currency) {
		return newPayoutError("unsupported_currency", merrors.InvalidArgument("currency is not allowed for this project", "currency"))
	}

	if strings.TrimSpace(req.GetCardToken()) == "" {
		return newPayoutError("missing_card_token", merrors.InvalidArgument("card_token is required", "card_token"))
	}

	if cfg.RequireCustomerAddress {
		if strings.TrimSpace(req.GetCustomerCountry()) == "" {
			return newPayoutError("missing_customer_country", merrors.InvalidArgument("customer_country is required", "customer_country"))
		}
		if strings.TrimSpace(req.GetCustomerCity()) == "" {
			return newPayoutError("missing_customer_city", merrors.InvalidArgument("customer_city is required", "customer_city"))
		}
		if strings.TrimSpace(req.GetCustomerAddress()) == "" {
			return newPayoutError("missing_customer_address", merrors.InvalidArgument("customer_address is required", "customer_address"))
		}
		if strings.TrimSpace(req.GetCustomerZip()) == "" {
			return newPayoutError("missing_customer_zip", merrors.InvalidArgument("customer_zip is required", "customer_zip"))
		}
	}

	return nil
}
