package model

import (
	"fmt"

	"github.com/tech/sendico/pkg/merrors"
	"go.mongodb.org/mongo-driver/v2/bson"
)

// TokenPaymentData represents a network or gateway-issued card token.
type TokenPaymentData struct {
	Token          string `bson:"token" json:"token"`
	Network        string `bson:"network,omitempty" json:"network,omitempty"`
	Last4          string `bson:"last4,omitempty" json:"last4,omitempty"`
	ExpMonth       string `bson:"expMonth,omitempty" json:"expMonth,omitempty"`
	ExpYear        string `bson:"expYear,omitempty" json:"expYear,omitempty"`
	CardholderName string `bson:"cardholderName,omitempty" json:"cardholderName,omitempty"`
	Country        string `bson:"country,omitempty" json:"country,omitempty"`
}

func (m *PaymentMethod) AsCardToken() (*TokenPaymentData, error) {
	if m.Type != PaymentTypeCardToken {
		return nil, merrors.InvalidArgument(fmt.Sprintf("payment method type is %s, not cardToken", m.Type), "type")
	}

	var d TokenPaymentData
	if err := bson.Unmarshal(m.Data, &d); err != nil {
		return nil, err
	}

	return &d, nil
}
