package validation

import (
	"GoMembership/internal/models"
	"GoMembership/internal/repositories"
	"GoMembership/pkg/errors"
	"GoMembership/pkg/logger"

	"github.com/go-playground/validator/v10"
)

func validateMembership(sl validator.StructLevel) {
	membership := sl.Current().Interface().(models.User).Membership
	if membership.SubscriptionModel.RequiredMembershipField != "" {
		switch membership.SubscriptionModel.RequiredMembershipField {
		case "ParentMembershipID":
			if err := CheckParentMembershipID(membership); err != nil {
				logger.Error.Printf("Error ParentMembershipValidation: %v", err.Error())
				sl.ReportError(membership.ParentMembershipID, membership.SubscriptionModel.RequiredMembershipField,
					"RequiredMembershipField", "invalid", "")
			}
		default:
			logger.Error.Printf("Error no matching RequiredMembershipField: %v", errors.ErrInvalidValue.Error())
			sl.ReportError(membership.ParentMembershipID, membership.SubscriptionModel.RequiredMembershipField,
				"RequiredMembershipField", "not_implemented", "")
		}

	}
}

func CheckParentMembershipID(membership models.Membership) error {

	if membership.ParentMembershipID == 0 {
		return errors.ValErrParentIDNotSet
	} else {
		_, err := repositories.GetUserByID(&membership.ParentMembershipID)
		if err != nil {
			return errors.ValErrParentIDNotFound
		}
	}
	return nil
}
