'use client' import { useQuery, useMutation, useQueryClient } from '@tanstack/react-query' import { apiClient } from '../client' import type { ApiFolder, ApiLabel, ApiIdentity } from '../types' export function useFolders(accountId?: string) { return useQuery({ queryKey: ['folders', accountId], queryFn: () => apiClient.get('/mail/folders', { account_id: accountId }), enabled: !!accountId, staleTime: 5 * 60_000, }) } export function useLabels() { return useQuery({ queryKey: ['labels'], queryFn: () => apiClient.get('/mail/labels'), staleTime: 5 * 60_000, }) } export function useCreateLabel() { const queryClient = useQueryClient() return useMutation({ mutationFn: (data: { name: string; color: string }) => apiClient.post('/mail/labels', data), onSuccess: () => { queryClient.invalidateQueries({ queryKey: ['labels'] }) }, }) } export function useUpdateLabel() { const queryClient = useQueryClient() return useMutation({ mutationFn: ({ id, ...data }: { id: string; name?: string; color?: string }) => apiClient.put(`/mail/labels/${id}`, data), onSuccess: () => { queryClient.invalidateQueries({ queryKey: ['labels'] }) }, }) } export function useDeleteLabel() { const queryClient = useQueryClient() return useMutation({ mutationFn: (id: string) => apiClient.delete(`/mail/labels/${id}`), onMutate: async (id) => { await queryClient.cancelQueries({ queryKey: ['labels'] }) const previous = queryClient.getQueryData(['labels']) queryClient.setQueryData(['labels'], (old) => old?.filter((l) => l.id !== id), ) return { previous } }, onError: (_err, _id, context) => { if (context?.previous) { queryClient.setQueryData(['labels'], context.previous) } }, onSettled: () => { queryClient.invalidateQueries({ queryKey: ['labels'] }) }, }) } export function useIdentities(accountId?: string) { return useQuery({ queryKey: ['identities', accountId], queryFn: () => apiClient.get(`/mail/accounts/${accountId}/identities`), enabled: !!accountId, }) }