import { useMutation, useQuery, useQueryClient } from '@tanstack/react-query'
import { toast } from 'sonner'
import { getRuns, getRun, createRun, updateRun, deleteRun } from '../api/runs'
import type { CreateRunInput, UpdateRunInput } from '../types/game'

export function useRuns() {
  return useQuery({
    queryKey: ['runs'],
    queryFn: getRuns,
  })
}

export function useRun(id: number) {
  return useQuery({
    queryKey: ['runs', id],
    queryFn: () => getRun(id),
  })
}

export function useCreateRun() {
  const queryClient = useQueryClient()
  return useMutation({
    mutationFn: (data: CreateRunInput) => createRun(data),
    onSuccess: () => {
      queryClient.invalidateQueries({ queryKey: ['runs'] })
    },
  })
}

export function useUpdateRun(id: number) {
  const queryClient = useQueryClient()
  return useMutation({
    mutationFn: (data: UpdateRunInput) => updateRun(id, data),
    onSuccess: (_result, data) => {
      queryClient.invalidateQueries({ queryKey: ['runs'] })
      queryClient.invalidateQueries({ queryKey: ['runs', id] })
      if (data.status === 'completed') toast.success('Run marked as completed!')
      else if (data.status === 'failed') toast.success('Run marked as failed')
      else toast.success('Run updated')
    },
    onError: (err) => toast.error(`Failed to update run: ${err.message}`),
  })
}

export function useDeleteRun() {
  const queryClient = useQueryClient()
  return useMutation({
    mutationFn: (id: number) => deleteRun(id),
    onSuccess: () => {
      queryClient.invalidateQueries({ queryKey: ['runs'] })
    },
  })
}
