/**
 * Daemon Event Handler
 *
 * Handles daemon events by updating React Query cache.
 * Extracted from useEventSubscription hook for use outside React.
 */
import { ISOTimestamp } from "@ghostflow/client/schemas";
import { flowKeys } from "@ghostflow/ui-core";
import { Array as Arr, Match, pipe, Schema as S } from "effect";
// ============================================================================
// Constants
// ============================================================================
/** Flow state constants */
const SYNCING_STATE = "syncing";
const IDLE_STATE = "idle";
const ERROR_STATE = "error";
// ============================================================================
// Logging
// ============================================================================
/** Log errors in development */
const logError = (context, error) => {
    if (process.env.NODE_ENV === "development") {
        console.debug(`[ghostflow] Error in ${context}:`, error);
    }
};
// ============================================================================
// Cache Update Helpers
// ============================================================================
/**
 * Create an ISO timestamp from the current time.
 */
const createISOTimestamp = () => S.decodeSync(ISOTimestamp)(new Date().toISOString());
/**
 * Update a specific flow in the cache by ID.
 */
const updateFlowById = (queryClient, flowId, transform) => {
    queryClient.setQueryData(flowKeys.lists(), (old) => {
        if (old == null)
            return old;
        return Arr.map(old, (flow) => (flow.id === flowId ? transform(flow) : flow));
    });
};
// ============================================================================
// Event Handlers
// ============================================================================
/** Handle sync_started event */
const handleSyncStarted = (queryClient, event) => updateFlowById(queryClient, event.flowId, (flow) => ({
    ...flow,
    state: SYNCING_STATE
}));
/** Handle sync_completed event */
const handleSyncCompleted = (queryClient, event) => updateFlowById(queryClient, event.flowId, (flow) => ({
    ...flow,
    state: IDLE_STATE,
    lastSync: createISOTimestamp(),
    lastError: undefined
}));
/** Handle sync_failed event */
const handleSyncFailed = (queryClient, event) => updateFlowById(queryClient, event.flowId, (flow) => ({
    ...flow,
    state: ERROR_STATE,
    lastError: event.error
}));
/** Fire-and-forget invalidation of flows query */
const invalidateFlowsQuery = (queryClient) => {
    queryClient.invalidateQueries({ queryKey: flowKeys.lists() }).catch((e) => logError("invalidateQueries", e));
};
/**
 * Handle incoming daemon events by updating the query cache.
 */
export const handleDaemonEvent = (queryClient, event) => pipe(Match.value(event), Match.when({ type: "flow_status_changed" }, ({ flowId, status }) => updateFlowById(queryClient, flowId, (flow) => ({
    ...flow,
    state: status.state,
    pendingChanges: status.pendingChanges,
    lastError: status.lastError,
    lastSync: status.lastSync
}))), Match.when({ type: "sync_started" }, (e) => handleSyncStarted(queryClient, e)), Match.when({ type: "sync_completed" }, (e) => handleSyncCompleted(queryClient, e)), Match.when({ type: "sync_failed" }, (e) => handleSyncFailed(queryClient, e)), Match.when({ type: "flow_added" }, () => invalidateFlowsQuery(queryClient)), Match.when({ type: "flow_removed" }, () => invalidateFlowsQuery(queryClient)), Match.exhaustive);
//# sourceMappingURL=eventHandler.js.map