package methods

import (
	"context"

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

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

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

	if req.GetCascade() {
		err = s.pmstore.DeleteCascade(ctx, accountRef, methodRef)
	} else {
		err = s.pmstore.Delete(ctx, accountRef, methodRef)
	}
	if err != nil {
		return autoError[methodsv1.DeletePaymentMethodResponse](ctx, s.logger, err)
	}

	return &methodsv1.DeletePaymentMethodResponse{}, nil
}
