import { useQuery, useMutation } from '@tanstack/react-query' import { api } from './client' export interface TaskEvent { id: number message: string level: string created_at: string } export interface TaskResult { id: number device_id: number status: string stdout: string | null stderr: string | null exit_code: number | null duration_ms: number | null executed_at: string | null } export interface Task { id: string type: string status: string target_scope: Record target_label: string | null params: Record result: { total: number; ok: number; failed: number } | null error_message: string | null created_by: number | null created_at: string started_at: string | null finished_at: string | null } export interface TaskDetail extends Task { events: TaskEvent[] device_results: TaskResult[] } export interface ActionInfo { name: string display_name: string compatible_categories: string[] params_schema: { name: string; type: string; label: string; required?: boolean }[] } export const useTasks = (page = 1, pageSize = 50) => useQuery({ queryKey: ['tasks', page, pageSize], queryFn: () => api .get('/api/v1/tasks', { params: { skip: (page - 1) * pageSize, limit: pageSize } }) .then((r) => r.data), refetchInterval: 5000, }) export const useTask = (id: string | undefined) => useQuery({ queryKey: ['tasks', id], queryFn: () => api.get(`/api/v1/tasks/${id}`).then((r) => r.data), enabled: !!id, refetchInterval: (query) => { const status = query.state.data?.status return status === 'running' || status === 'pending' ? 2000 : false }, }) export const useActions = () => useQuery({ queryKey: ['actions'], queryFn: () => api.get('/api/v1/tasks/actions').then((r) => r.data), }) export const useCreateTask = () => useMutation({ mutationFn: (body: { type: string; target_scope: object; params: object }) => api.post('/api/v1/tasks', body).then((r) => r.data), }) export const useDeviceTasks = (deviceId: number) => useQuery({ queryKey: ['tasks', 'device', deviceId], queryFn: () => api .get('/api/v1/tasks', { params: { device_id: deviceId, limit: 100 } }) .then((r) => r.data), })