All files / web/src/hooks usePlayerAbacusIdentity.ts

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

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                                                                                                                                                               
'use client'

import { useMutation, useQuery, useQueryClient } from '@tanstack/react-query'
import type { AbacusIdentity } from '@/lib/abacus/identity'
import { api } from '@/lib/queryClient'
import { playerAbacusIdentityKeys } from '@/lib/queryKeys'

interface AbacusIdentityResponse {
  identity: AbacusIdentity
}

async function fetchAbacusIdentity(playerId: string): Promise<AbacusIdentity> {
  const res = await api(`players/${playerId}/abacus-identity`)
  if (!res.ok) throw new Error('Failed to fetch abacus identity')
  const data: AbacusIdentityResponse = await res.json()
  return data.identity
}

async function saveAbacusIdentity(
  playerId: string,
  identity: AbacusIdentity
): Promise<AbacusIdentity> {
  const res = await api(`players/${playerId}/abacus-identity`, {
    method: 'PUT',
    headers: { 'Content-Type': 'application/json' },
    body: JSON.stringify({ identity }),
  })
  if (!res.ok) throw new Error('Failed to save abacus identity')
  const data: AbacusIdentityResponse = await res.json()
  return data.identity
}

/**
 * Hook: Fetch a player's "my abacus" identity (server answers the stock
 * defaults when the player has no saved row)
 */
export function usePlayerAbacusIdentity(playerId: string | null) {
  return useQuery({
    queryKey: playerAbacusIdentityKeys.detail(playerId ?? 'anonymous'),
    queryFn: () => fetchAbacusIdentity(playerId as string),
    enabled: Boolean(playerId),
    // Identity changes only via an explicit save — keep stale longer
    staleTime: 1000 * 60 * 30,
  })
}

/**
 * Hook: Save a player's abacus identity with optimistic update
 */
export function useSavePlayerAbacusIdentity(playerId: string) {
  const queryClient = useQueryClient()

  return useMutation({
    mutationFn: (identity: AbacusIdentity) => saveAbacusIdentity(playerId, identity),
    onMutate: async (identity) => {
      await queryClient.cancelQueries({
        queryKey: playerAbacusIdentityKeys.detail(playerId),
      })

      const previous = queryClient.getQueryData<AbacusIdentity>(
        playerAbacusIdentityKeys.detail(playerId)
      )

      queryClient.setQueryData(playerAbacusIdentityKeys.detail(playerId), identity)

      return { previous }
    },
    onError: (_err, _identity, context) => {
      if (context?.previous !== undefined) {
        queryClient.setQueryData(playerAbacusIdentityKeys.detail(playerId), context.previous)
      }
    },
    onSettled: (savedIdentity) => {
      if (savedIdentity) {
        queryClient.setQueryData(playerAbacusIdentityKeys.detail(playerId), savedIdentity)
      }
    },
  })
}