/**
 * Hook for creating a new node
 */

import { useMutation, useQueryClient } from '@tanstack/react-query';
import { useSetAtom } from 'jotai';
import type { DBGraphNode } from '../../core/types';
import { startMutationAtom, completeMutationAtom } from '../../core/sync-store';
import { useSupabaseClient } from '../provider';
import { createGraphNode } from '../queries/nodes';
import { canvasKeys } from './keys';

export type CreateNodeVariables = Omit<DBGraphNode, 'id' | 'created_at' | 'updated_at'>;

/**
 * Hook to create a new node
 */
export function useCreateNode() {
	const queryClient = useQueryClient();
	const supabase = useSupabaseClient();
	const startMutation = useSetAtom(startMutationAtom);
	const completeMutation = useSetAtom(completeMutationAtom);

	return useMutation({
		mutationFn: async (node: CreateNodeVariables) => {
			return createGraphNode(supabase, node);
		},
		onMutate: async (node) => {
			startMutation();

			// Cancel any outgoing refetches
			await queryClient.cancelQueries({ queryKey: canvasKeys.nodes(node.graph_id) });

			// Snapshot the previous value
			const previousNodes = queryClient.getQueryData<DBGraphNode[]>(canvasKeys.nodes(node.graph_id));

			// Optimistically add the new node with a temporary ID
			const optimisticNode: DBGraphNode = {
				...node,
				id: `temp-${Date.now()}`,
				created_at: new Date().toISOString(),
				updated_at: new Date().toISOString(),
			};

			queryClient.setQueryData<DBGraphNode[]>(canvasKeys.nodes(node.graph_id), (old) => [...(old || []), optimisticNode]);

			return { previousNodes, graphId: node.graph_id, optimisticId: optimisticNode.id };
		},
		onError: (_err, _variables, context) => {
			// Rollback on error
			if (context?.previousNodes) {
				queryClient.setQueryData(canvasKeys.nodes(context.graphId), context.previousNodes);
			}
			completeMutation(false);
		},
		onSuccess: (newNode, _variables, context) => {
			// Replace optimistic node with real node
			if (context) {
				queryClient.setQueryData<DBGraphNode[]>(canvasKeys.nodes(context.graphId), (old) =>
					old?.map((node) => (node.id === context.optimisticId ? newNode : node)),
				);
			}
			completeMutation(true);
		},
		onSettled: (_data, _error, variables) => {
			// Invalidate to ensure fresh data
			queryClient.invalidateQueries({ queryKey: canvasKeys.nodes(variables.graph_id) });
		},
	});
}
