/**
 * Hook for updating an edge with optimistic updates
 */

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 { updateGraphEdge } from '../queries/edges';
import { canvasKeys } from './keys';

export interface UpdateEdgeVariables {
	edgeId: string;
	graphId: string;
	updates: Partial<Pick<DBGraphEdge, 'edge_type' | 'filter_condition' | 'ui_properties'>>;
}

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

	return useMutation({
		mutationFn: async ({ edgeId, updates }: UpdateEdgeVariables) => {
			return updateGraphEdge(supabase, edgeId, updates);
		},
		onMutate: async ({ edgeId, graphId, updates }) => {
			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 update the cache
			if (previousEdges) {
				queryClient.setQueryData<DBGraphEdge[]>(canvasKeys.edges(graphId), (old) =>
					old?.map((edge) =>
						edge.id === edgeId
							? {
									...edge,
									...updates,
									updated_at: new Date().toISOString(),
								}
							: edge,
					),
				);
			}

			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) });
		},
	});
}
