/**
 * Hook for deleting a 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 { deleteGraphNode } from '../queries/nodes';
import { canvasKeys } from './keys';

export interface DeleteNodeVariables {
	nodeId: string;
	graphId: string;
}

/**
 * Hook to delete a node with optimistic updates
 */
export function useDeleteNode() {
	const queryClient = useQueryClient();
	const supabase = useSupabaseClient();
	const startMutation = useSetAtom(startMutationAtom);
	const completeMutation = useSetAtom(completeMutationAtom);

	return useMutation({
		mutationFn: async ({ nodeId }: DeleteNodeVariables) => {
			return deleteGraphNode(supabase, nodeId);
		},
		onMutate: async ({ nodeId, graphId }) => {
			startMutation();

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

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

			// Optimistically remove the node
			if (previousNodes) {
				queryClient.setQueryData<DBGraphNode[]>(canvasKeys.nodes(graphId), (old) =>
					old?.filter((node) => node.id !== nodeId),
				);
			}

			return { previousNodes, graphId };
		},
		onError: (_err, _variables, context) => {
			// Rollback on error
			if (context?.previousNodes) {
				queryClient.setQueryData(canvasKeys.nodes(context.graphId), context.previousNodes);
			}
			completeMutation(false);
		},
		onSuccess: () => {
			completeMutation(true);
		},
		onSettled: (_data, _error, variables) => {
			// Invalidate to ensure fresh data
			queryClient.invalidateQueries({ queryKey: canvasKeys.nodes(variables.graphId) });
		},
	});
}
