/**
 * Builds the connection object for the widget configuration.
 * Ensures the widget key from URL is passed through for event tracking.
 *
 * @param key - The widget key from the URL
 * @param existingConnection - The connection object from the config JSON (may be undefined)
 * @returns The connection object with accountKey set
 */
export function buildConnection(
    key: string | null | undefined,
    existingConnection: { accountKey?: string; serverUrl?: string } | undefined | null
): { accountKey?: string; serverUrl?: string } | undefined {
    // If we have a key from URL and the existing connection doesn't have accountKey,
    // create/extend the connection with the URL key
    if (key && !existingConnection?.accountKey) {
        return { ...(existingConnection || {}), accountKey: key };
    }
    return existingConnection ?? undefined;
}
