import { useQuery, useMutation, useQueryClient } from '@tanstack/react-query'
import { useAuthStore } from '@/store/auth-store'
import {
  fetchGamification,
  fetchXuTransactions,
  fetchLeaderboard,
  awardActivity,
} from '@/lib/gamification-service'

export function useGamification() {
  const user = useAuthStore((s) => s.user)
  return useQuery({
    queryKey: ['gamification', user?.id],
    queryFn: () => fetchGamification(user!.id),
    enabled: !!user,
    staleTime: 30_000,
  })
}

export function useXuTransactions(limit = 10) {
  const user = useAuthStore((s) => s.user)
  return useQuery({
    queryKey: ['xu-transactions', user?.id, limit],
    queryFn: () => fetchXuTransactions(user!.id, limit),
    enabled: !!user,
    staleTime: 30_000,
  })
}

export function useLeaderboard() {
  return useQuery({
    queryKey: ['leaderboard'],
    queryFn: fetchLeaderboard,
    staleTime: 60_000,
  })
}

export function useAwardActivity() {
  const user = useAuthStore((s) => s.user)
  const queryClient = useQueryClient()

  return useMutation({
    mutationFn: ({ xp }: { xp: number }) =>
      awardActivity(user!.id, xp, user!.name),
    onSuccess: () => {
      queryClient.invalidateQueries({ queryKey: ['gamification', user?.id] })
      queryClient.invalidateQueries({ queryKey: ['xu-transactions', user?.id] })
      queryClient.invalidateQueries({ queryKey: ['leaderboard'] })
    },
  })
}
