package methods

import (
	"context"

	"github.com/tech/sendico/pkg/merrors"
	methodsv1 "github.com/tech/sendico/pkg/proto/payments/methods/v1"
)

func (s *Service) CreatePaymentMethod(ctx context.Context, req *methodsv1.CreatePaymentMethodRequest) (*methodsv1.CreatePaymentMethodResponse, error) {
	if req == nil {
		return autoError[methodsv1.CreatePaymentMethodResponse](ctx, s.logger, merrors.InvalidArgument("request is required"))
	}
	if s.pmstore == nil {
		return autoError[methodsv1.CreatePaymentMethodResponse](ctx, s.logger, errStoreUnavailable)
	}

	accountRef, err := parseObjectID(req.GetAccountRef(), "account_ref")
	if err != nil {
		return autoError[methodsv1.CreatePaymentMethodResponse](ctx, s.logger, err)
	}
	organizationRef, err := parseObjectID(req.GetOrganizationRef(), "organization_ref")
	if err != nil {
		return autoError[methodsv1.CreatePaymentMethodResponse](ctx, s.logger, err)
	}

	pm, err := decodePaymentMethodPayload(req.GetPaymentMethod(), "payment_method")
	if err != nil {
		return autoError[methodsv1.CreatePaymentMethodResponse](ctx, s.logger, err)
	}
	if err := s.pmstore.Create(ctx, accountRef, organizationRef, pm); err != nil {
		return autoError[methodsv1.CreatePaymentMethodResponse](ctx, s.logger, err)
	}

	record, err := encodePaymentMethodRecord(pm)
	if err != nil {
		return autoError[methodsv1.CreatePaymentMethodResponse](ctx, s.logger, err)
	}

	return &methodsv1.CreatePaymentMethodResponse{PaymentMethodRecord: record}, nil
}
