package methods

import (
	"context"

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

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

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

	pm, err := s.pmstore.Get(ctx, accountRef, methodRef)
	if err != nil {
		return autoError[methodsv1.GetPaymentMethodResponse](ctx, s.logger, err)
	}

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

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