import { useMutation, useQuery, useQueryClient } from '@tanstack/react-query'
import { toast } from 'sonner'
import { getGameBosses, getBossResults, createBossResult, deleteBossResult } from '../api/bosses'
import type { CreateBossResultInput } from '../types/game'

export function useGameBosses(gameId: number | null) {
  return useQuery({
    queryKey: ['games', gameId, 'bosses'],
    queryFn: () => getGameBosses(gameId!),
    enabled: gameId != null,
  })
}

export function useBossResults(runId: number) {
  return useQuery({
    queryKey: ['runs', runId, 'boss-results'],
    queryFn: () => getBossResults(runId),
  })
}

export function useCreateBossResult(runId: number) {
  const qc = useQueryClient()
  return useMutation({
    mutationFn: (data: CreateBossResultInput) => createBossResult(runId, data),
    onSuccess: () => {
      qc.invalidateQueries({ queryKey: ['runs', runId, 'boss-results'] })
      toast.success('Boss result recorded')
    },
    onError: (err) => toast.error(`Failed to record result: ${err.message}`),
  })
}

export function useDeleteBossResult(runId: number) {
  const qc = useQueryClient()
  return useMutation({
    mutationFn: (resultId: number) => deleteBossResult(runId, resultId),
    onSuccess: () => {
      qc.invalidateQueries({ queryKey: ['runs', runId, 'boss-results'] })
      toast.success('Boss result removed')
    },
    onError: (err) => toast.error(`Failed to remove result: ${err.message}`),
  })
}
