/**
 * Edges Slice - 边状态管理
 */
import { Edge, EdgeChange, Connection as FlowConnection, addEdge } from '@xyflow/react';
import { applyEdgeChanges } from '@xyflow/react';
import { CanvasState } from './types';

export const createEdgesActions = (set: any, get: any) => ({
    setEdges: (updater: Edge[] | ((prev: Edge[]) => Edge[])) => set((state: CanvasState) => {
        state.edges = typeof updater === 'function' ? updater(state.edges) : updater;
        state.isDirty = true;
    }),

    onEdgesChange: (changes: EdgeChange[]) => set((state: CanvasState) => {
        state.edges = applyEdgeChanges(changes, state.edges);
        state.isDirty = true;

        const hasMeaningfulChange = changes.some(c => c.type === 'remove' || c.type === 'add');
        if (hasMeaningfulChange) {
            get().saveHistoryThrottled();
        }
    }),

    onConnect: (connection: FlowConnection) => set((state: CanvasState) => {
        state.edges = addEdge(connection, state.edges);
        get().saveHistory();
    }),
});
