import { useMutation, useQuery, useQueryClient } from '@tanstack/react-query'
import { advanceLeg, createGenlocke, getGamesByRegion, getGenlockes, getGenlocke, getGenlockeGraveyard, getGenlockeLineages, getLegSurvivors } from '../api/genlockes'
import type { CreateGenlockeInput } from '../types/game'

export function useGenlockes() {
  return useQuery({
    queryKey: ['genlockes'],
    queryFn: getGenlockes,
  })
}

export function useGenlocke(id: number) {
  return useQuery({
    queryKey: ['genlockes', id],
    queryFn: () => getGenlocke(id),
  })
}

export function useGenlockeGraveyard(id: number) {
  return useQuery({
    queryKey: ['genlockes', id, 'graveyard'],
    queryFn: () => getGenlockeGraveyard(id),
  })
}

export function useGenlockeLineages(id: number) {
  return useQuery({
    queryKey: ['genlockes', id, 'lineages'],
    queryFn: () => getGenlockeLineages(id),
  })
}

export function useRegions() {
  return useQuery({
    queryKey: ['games', 'by-region'],
    queryFn: getGamesByRegion,
  })
}

export function useCreateGenlocke() {
  const queryClient = useQueryClient()
  return useMutation({
    mutationFn: (data: CreateGenlockeInput) => createGenlocke(data),
    onSuccess: () => {
      queryClient.invalidateQueries({ queryKey: ['runs'] })
      queryClient.invalidateQueries({ queryKey: ['genlockes'] })
    },
  })
}

export function useLegSurvivors(genlockeId: number, legOrder: number, enabled: boolean) {
  return useQuery({
    queryKey: ['genlockes', genlockeId, 'legs', legOrder, 'survivors'],
    queryFn: () => getLegSurvivors(genlockeId, legOrder),
    enabled,
  })
}

export function useAdvanceLeg() {
  const queryClient = useQueryClient()
  return useMutation({
    mutationFn: ({ genlockeId, legOrder, transferEncounterIds }: { genlockeId: number; legOrder: number; transferEncounterIds?: number[] }) =>
      advanceLeg(genlockeId, legOrder, transferEncounterIds ? { transferEncounterIds } : undefined),
    onSuccess: () => {
      queryClient.invalidateQueries({ queryKey: ['runs'] })
      queryClient.invalidateQueries({ queryKey: ['genlockes'] })
    },
  })
}
