/**
 * Decodes a Relay Global ID to extract the raw ID.
 * @param globalId The Base64-encoded Relay ID (e.g., "Q3VzdG9tZXJUeXBlOjE=")
 * @returns The raw ID (e.g., "1")
 */
export function fromGlobalId(globalId: string): string {
	if (!globalId) return '';

	let decoded: string;
	try {
		decoded = atob(globalId);
	} catch (e) {
		console.error('Failed to decode global ID:', e);
		return '';
	}

	const sep = decoded.indexOf(':');
	if (sep <= 0 || sep === decoded.length - 1) {
		// Silently fail for invalid Global ID format
		return '';
	}

	return decoded.slice(sep + 1);
}

/**
 * Encodes a raw ID and type name into a Relay Global ID.
 * @param typeName The GraphQL object type (e.g., 'CustomerType')
 * @param id The raw ID (e.g., "1")
 * @returns The Base64-encoded Relay ID (e.g., "Q3VzdG9tZXJUeXBlOjE=")
 */
export function toGlobalId(typeName: string, id: string): string {
	if (!typeName || !id) {
		console.error('Both typeName and id must be provided for encoding.');
		return '';
	}
	return btoa(`${typeName}:${id}`);
}
