import type { UiNode, UiNodeInputAttributes } from '@ory/client';

export function getNodeLabel(node: UiNode): string {
	const attrs = node.attributes as UiNodeInputAttributes;
	if (node.meta.label?.text) {
		return node.meta.label.text;
	}
	return attrs.name || '';
}

export function filterNodesByGroups(nodes: UiNode[], ...groups: string[]): UiNode[] {
	return nodes.filter((node) => groups.includes(node.group));
}

/**
 * Helper function to set nested property in an object using dot notation
 * Example: setNestedProperty(obj, 'traits.name.first', 'John')
 */
export function setNestedProperty(obj: any, path: string, value: any): void {
	const keys = path.split('.');
	let current = obj;

	for (let i = 0; i < keys.length - 1; i++) {
		const key = keys[i];
		if (!(key in current)) {
			current[key] = {};
		}
		current = current[key];
	}

	current[keys[keys.length - 1]] = value;
}

/**
 * Convert FormData to JSON object for Ory SDK submission
 * This handles nested properties (like traits.email, traits.name.first)
 * and includes the csrf_token which must be present in JSON requests
 */
export function formDataToJson(formData: FormData): Record<string, any> {
	const json: Record<string, any> = {};

	for (const [key, value] of formData.entries()) {
		// Handle nested object notation (e.g., traits.email, traits.name.first)
		if (key.includes('.')) {
			setNestedProperty(json, key, value);
		} else {
			json[key] = value;
		}
	}

	return json;
}
