package methods

import (
	"context"

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

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

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

	pm, err := decodePaymentMethodRecord(req.GetPaymentMethodRecord())
	if err != nil {
		return autoError[methodsv1.UpdatePaymentMethodResponse](ctx, s.logger, err)
	}
	if err := s.pmstore.Update(ctx, accountRef, pm); err != nil {
		return autoError[methodsv1.UpdatePaymentMethodResponse](ctx, s.logger, err)
	}

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

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