import { useQuery, useMutation, useQueryClient } from '@tanstack/react-query'; import { toast } from 'sonner'; import { peopleApi } from '@/api/people'; export const peopleKeys = { all: ['people'] as const, detail: (id: number) => ['people', id] as const, credits: (id: number) => ['people', id, 'credits'] as const, tmdbFilmography: (id: number) => ['people', id, 'tmdb-filmography'] as const, }; export function usePerson(id: number) { return useQuery({ queryKey: peopleKeys.detail(id), queryFn: () => peopleApi.getById(id), enabled: !!id, }); } export function usePersonCredits(id: number) { return useQuery({ queryKey: peopleKeys.credits(id), queryFn: () => peopleApi.getCredits(id), enabled: !!id, }); } export function usePersonTmdbFilmography(id: number) { return useQuery({ queryKey: peopleKeys.tmdbFilmography(id), queryFn: () => peopleApi.getTmdbFilmography(id), enabled: !!id, staleTime: 10 * 60 * 1000, }); } export function useFetchPersonByTmdbId() { return useMutation({ mutationFn: (tmdb_id: number) => peopleApi.fetchByTmdbId(tmdb_id), }); } export function useUpdatePerson() { const queryClient = useQueryClient(); return useMutation({ mutationFn: ({ id, data }: { id: number; data: Partial }) => peopleApi.update(id, data), onSuccess: (updatedPerson) => { queryClient.invalidateQueries({ queryKey: peopleKeys.detail(updatedPerson.id) }); toast.success('Person updated'); }, onError: () => { toast.error('Failed to update person'); }, }); } export function useSearchLocalPeople(query: string) { return useQuery({ queryKey: ['people', 'search', query], queryFn: () => query === '*' ? peopleApi.getAll() : peopleApi.search(query), enabled: query.length > 0, }); }