All files / web/src/hooks useVersionHistory.ts

0% Statements 0/106
0% Branches 0/1
0% Functions 0/1
0% Lines 0/106

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107                                                                                                                                                                                                                     
'use client'

import { useMutation, useQuery, useQueryClient } from '@tanstack/react-query'
import { versionHistoryKeys } from '@/lib/queryKeys'

// Re-export query keys for consumers
export { versionHistoryKeys } from '@/lib/queryKeys'

export interface FlowchartVersion {
  id: string
  versionNumber: number
  source: 'generate' | 'refine'
  sourceRequest: string | null
  emoji: string | null
  title: string | null
  description: string | null
  difficulty: string | null
  notes: string | null
  validationPassed: boolean | null
  coveragePercent: number | null
  createdAt: string
  isCurrent: boolean
  // Full data for preview (returned by API but may be large)
  definitionJson: string
  mermaidContent: string
}

interface VersionHistoryResponse {
  versions: FlowchartVersion[]
  currentVersion: number
}

/**
 * Fetch version history for a session
 */
async function fetchVersionHistory(sessionId: string): Promise<VersionHistoryResponse> {
  const res = await fetch(`/api/flowchart-workshop/sessions/${sessionId}/versions`)
  if (!res.ok) {
    throw new Error('Failed to fetch version history')
  }
  return res.json()
}

/**
 * Restore a specific version
 */
async function restoreVersion({
  sessionId,
  versionNumber,
}: {
  sessionId: string
  versionNumber: number
}): Promise<{ success: boolean }> {
  const res = await fetch(`/api/flowchart-workshop/sessions/${sessionId}/versions`, {
    method: 'POST',
    headers: { 'Content-Type': 'application/json' },
    body: JSON.stringify({ versionNumber }),
  })
  if (!res.ok) {
    throw new Error('Failed to restore version')
  }
  return res.json()
}

/**
 * Hook: Fetch version history for a session
 */
export function useVersionHistory(sessionId: string) {
  return useQuery({
    queryKey: versionHistoryKeys.session(sessionId),
    queryFn: () => fetchVersionHistory(sessionId),
    // Refetch when window regains focus (catches versions created in other tabs)
    refetchOnWindowFocus: true,
  })
}

/**
 * Hook: Restore a version
 */
export function useRestoreVersion(sessionId: string) {
  const queryClient = useQueryClient()

  return useMutation({
    mutationFn: (versionNumber: number) => restoreVersion({ sessionId, versionNumber }),
    onSuccess: () => {
      // Invalidate the version history to refresh the list with new current marker
      queryClient.invalidateQueries({
        queryKey: versionHistoryKeys.session(sessionId),
      })
    },
  })
}

/**
 * Hook: Get a function to invalidate version history cache
 * Call this after generate/refine completes to refresh the history tab
 */
export function useInvalidateVersionHistory() {
  const queryClient = useQueryClient()

  return (sessionId: string) => {
    queryClient.invalidateQueries({
      queryKey: versionHistoryKeys.session(sessionId),
    })
  }
}