# ======= SHARED HELPERS =======

import frappe


def resolve_customer_group(preferred=None):
	"""Return a usable (non-group) Customer Group, or None.

	Newer ERPNext rejects assigning a Customer to a "group" type Customer Group
	(e.g. the root "All Customer Groups"), and `customer_group` is no longer a
	mandatory field. So:
	  - if a valid, non-group Customer Group is configured -> use it
	  - otherwise return None and let the Customer be created without a group
	"""
	if preferred and frappe.db.exists("Customer Group", preferred):
		if not frappe.db.get_value("Customer Group", preferred, "is_group"):
			return preferred
	return None


def resolve_territory(preferred=None):
	"""Return a usable Territory, or None if the configured one is missing.

	Mirrors :func:`resolve_customer_group`; Territory root nodes are still
	accepted by ERPNext, so we only validate existence.
	"""
	if preferred and frappe.db.exists("Territory", preferred):
		return preferred
	return None
