package methods

import (
	"context"

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

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

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

	items, err := s.pmstore.List(ctx, accountRef, organizationRef, recipientRef, toModelCursor(req.GetCursor()))
	if err != nil {
		return autoError[methodsv1.ListPaymentMethodsResponse](ctx, s.logger, err)
	}

	result := make([]*endpointv1.PaymentMethodRecord, 0, len(items))
	for i := range items {
		record, err := encodePaymentMethodRecord(&items[i])
		if err != nil {
			return autoError[methodsv1.ListPaymentMethodsResponse](ctx, s.logger, err)
		}
		result = append(result, record)
	}

	return &methodsv1.ListPaymentMethodsResponse{
		PaymentMethods: result,
	}, nil
}
