/**
 * Hook for deleting an edge
 */

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

export interface DeleteEdgeVariables {
	edgeId: string;
	graphId: string;
}

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

	return useMutation({
		mutationFn: async ({ edgeId }: DeleteEdgeVariables) => {
			return deleteGraphEdge(supabase, edgeId);
		},
		onMutate: async ({ edgeId, graphId }) => {
			startMutation();

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

			// Snapshot the previous value
			const previousEdges = queryClient.getQueryData<DBGraphEdge[]>(canvasKeys.edges(graphId));

			// Optimistically remove the edge
			if (previousEdges) {
				queryClient.setQueryData<DBGraphEdge[]>(canvasKeys.edges(graphId), (old) =>
					old?.filter((edge) => edge.id !== edgeId),
				);
			}

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