/**
 * Connected Node Component
 *
 * A batteries-included node that automatically persists changes to Supabase.
 * Apps only need to provide the Supabase URL and run migrations.
 */

import React from 'react';
import { Node, type NodeProps } from './Node';
import type { NodeId, UINodeProperties } from '../core/types';
import { useUpdateNode } from '../db/hooks/useUpdateNode';
import { createDebug } from '../utils/debug';

const debug = createDebug('connected-node');

// Re-export types for convenience
export type { NodeRenderProps } from './Node';

export interface ConnectedNodeProps extends Omit<NodeProps, 'onPersist' | 'onPersistError'> {
	/** Optional callback when persist fails (for custom error handling) */
	onPersistError?: (nodeId: NodeId, error: Error) => void;
}

/**
 * Node component with automatic Supabase persistence.
 *
 * Wraps the base Node component and auto-wires the `useUpdateNode`
 * hook for database persistence.
 */
export function ConnectedNode({
	nodeData,
	renderContent,
	onPersistError: customErrorHandler,
	wrapper,
}: ConnectedNodeProps) {
	const { mutateAsync: updateNode } = useUpdateNode();

	const handlePersist = async (nodeId: NodeId, graphId: string, uiProperties: UINodeProperties) => {
		debug('Persisting node %s to graph %s', nodeId, graphId);
		await updateNode({
			nodeId,
			graphId,
			updates: { ui_properties: uiProperties },
		});
	};

	const handlePersistError = (nodeId: NodeId, error: Error) => {
		debug('Failed to persist node %s: %o', nodeId, error);
		customErrorHandler?.(nodeId, error);
	};

	return (
		<Node
			nodeData={nodeData}
			renderContent={renderContent}
			onPersist={handlePersist}
			onPersistError={handlePersistError}
			wrapper={wrapper}
		/>
	);
}
