All files / web/src/hooks useDebugSeedStudents.ts

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

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 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                             
'use client'

import { useMutation, useQuery, useQueryClient } from '@tanstack/react-query'
import { api } from '@/lib/queryClient'
import { debugKeys } from '@/lib/queryKeys'
import type { ProfileInfo, ProfileCategory } from '@/lib/seed/types'

// ── Query types ────────────────────────────────────────────────────────────────

interface SeedProfilesResponse {
  profiles: ProfileInfo[]
  categories: ProfileCategory[]
}

interface EmbeddingStatus {
  cached: boolean
  stale: boolean
  profileCount: number
  cachedAt: string | null
}

interface SeededStudentInfo {
  playerId: string
  seededAt: string
}

interface SearchResult {
  name: string
  similarity: number
}

// ── Queries ────────────────────────────────────────────────────────────────────

/** Fetch available seed profiles */
export function useSeedProfiles() {
  return useQuery({
    queryKey: debugKeys.seedProfiles(),
    queryFn: async (): Promise<SeedProfilesResponse> => {
      const res = await api('debug/seed-students')
      if (!res.ok) throw new Error(`HTTP ${res.status}`)
      return res.json()
    },
  })
}

/** Fetch embedding status for semantic search */
export function useEmbeddingStatus() {
  return useQuery({
    queryKey: debugKeys.seedEmbeddingStatus(),
    queryFn: async (): Promise<EmbeddingStatus> => {
      const res = await api('debug/seed-students/embeddings')
      if (!res.ok) throw new Error(`HTTP ${res.status}`)
      return res.json()
    },
  })
}

/** Fetch previously-seeded students */
export function useSeededStudents() {
  return useQuery({
    queryKey: debugKeys.seededStudents(),
    queryFn: async (): Promise<Record<string, SeededStudentInfo>> => {
      const res = await api('debug/seed-students/seeded')
      if (!res.ok) throw new Error(`HTTP ${res.status}`)
      const data = await res.json()
      return data.seeded ?? {}
    },
  })
}

/** Semantic search for profiles (only enabled when query is >= 3 chars) */
export function useSeedProfileSearch(query: string) {
  const trimmed = query.trim()
  return useQuery({
    queryKey: debugKeys.seedSearch(trimmed),
    queryFn: async (): Promise<Map<string, number>> => {
      const res = await api(`debug/seed-students/search?q=${encodeURIComponent(trimmed)}`)
      if (!res.ok) throw new Error(`HTTP ${res.status}`)
      const data = await res.json()
      const map = new Map<string, number>()
      for (const r of (data.results ?? []) as SearchResult[]) {
        map.set(r.name, r.similarity)
      }
      return map
    },
    enabled: trimmed.length >= 3,
    // Keep previous results visible while refetching a new query
    placeholderData: (prev) => prev,
  })
}

// ── Mutations ──────────────────────────────────────────────────────────────────

/** Regenerate search embeddings */
export function useRegenerateEmbeddings() {
  const queryClient = useQueryClient()
  return useMutation({
    mutationFn: async (): Promise<EmbeddingStatus> => {
      const res = await api('debug/seed-students/embeddings', { method: 'POST' })
      if (!res.ok) throw new Error(`HTTP ${res.status}`)
      return res.json()
    },
    onSuccess: (data) => {
      queryClient.setQueryData(debugKeys.seedEmbeddingStatus(), data)
    },
  })
}

/** Start seeding students (returns a background task ID) */
export function useSeedStudents() {
  return useMutation({
    mutationFn: async (
      profileNames: string[]
    ): Promise<{ taskId: string; profileCount: number }> => {
      const res = await api('debug/seed-students', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({ profiles: profileNames }),
      })
      if (!res.ok) {
        const data = await res.json()
        throw new Error(data.error || `HTTP ${res.status}`)
      }
      return res.json()
    },
  })
}

// ── Cleanup ─────────────────────────────────────────────────────────────────

interface CleanupCandidate {
  id: string
  name: string
  emoji: string
  color: string
  createdAt: string
  source: string
}

interface CleanupPreviewResponse {
  players: CleanupCandidate[]
  count: number
}

interface CleanupDeleteResponse {
  deleted: number
  players: { id: string; name: string; source: string }[]
}

/** Preview debug/seed players that would be deleted */
export function useCleanupPreview(enabled: boolean) {
  return useQuery({
    queryKey: debugKeys.cleanupPreview(),
    queryFn: async (): Promise<CleanupPreviewResponse> => {
      const res = await api('debug/cleanup')
      if (!res.ok) throw new Error(`HTTP ${res.status}`)
      return res.json()
    },
    enabled,
  })
}

/** Delete all debug/seed players */
export function useCleanupDebugPlayers() {
  const queryClient = useQueryClient()
  return useMutation({
    mutationFn: async (): Promise<CleanupDeleteResponse> => {
      const res = await api('debug/cleanup', { method: 'DELETE' })
      if (!res.ok) {
        const data = await res.json()
        throw new Error(data.error || `HTTP ${res.status}`)
      }
      return res.json()
    },
    onSuccess: () => {
      queryClient.invalidateQueries({ queryKey: debugKeys.cleanupPreview() })
      queryClient.invalidateQueries({ queryKey: debugKeys.seededStudents() })
      // Also invalidate the players list so the practice page refreshes
      queryClient.invalidateQueries({ queryKey: ['players'] })
    },
  })
}

/** Create a debug practice session */
export function useCreateDebugPracticeSession() {
  return useMutation({
    mutationFn: async (params: {
      preset: string
      setupOnly: boolean
      simulateFamilyTier?: boolean
    }): Promise<{
      setupOnly?: boolean
      playerId?: string
      playerName?: string
      redirectUrl?: string
    }> => {
      const res = await api('debug/practice-session', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify(params),
      })
      if (!res.ok) {
        const data = await res.json()
        throw new Error(data.error || `HTTP ${res.status}`)
      }
      return res.json()
    },
  })
}

/** Fetch build info */
export function useBuildInfo() {
  return useQuery({
    queryKey: debugKeys.buildInfo(),
    queryFn: async (): Promise<Record<string, unknown>> => {
      const res = await fetch('/api/build-info')
      if (!res.ok) throw new Error(`HTTP ${res.status}`)
      return res.json()
    },
    staleTime: 30_000,
  })
}

/** Sync billing from Stripe */
export function useBillingSync() {
  const queryClient = useQueryClient()
  return useMutation({
    mutationFn: async (): Promise<{ sessionId: string }> => {
      const res = await api('debug/billing-sync', { method: 'POST' })
      const data = await res.json()
      if (!res.ok) throw new Error(data.error || `HTTP ${res.status}`)
      return data
    },
    onSuccess: () => {
      // billingKeys is imported in the component that uses this
      queryClient.invalidateQueries({ queryKey: ['billing'] })
    },
  })
}

/** Reset billing subscription */
export function useBillingReset() {
  const queryClient = useQueryClient()
  return useMutation({
    mutationFn: async (): Promise<void> => {
      const res = await api('debug/billing-reset', { method: 'POST' })
      const data = await res.json()
      if (!res.ok) throw new Error(data.error || `HTTP ${res.status}`)
    },
    onSuccess: () => {
      queryClient.invalidateQueries({ queryKey: ['billing'] })
    },
  })
}