import { useQuery, useMutation, useQueryClient } from "@tanstack/react-query"; export interface WeeklyReport { id: number; clientId: number; fileName: string; fileUrl: string; fileSize: number; mimeType: string; uploadedByUserId: number; createdAt: string; } function getAuthHeaders(): HeadersInit { const token = localStorage.getItem("teamtasker_token"); return token ? { Authorization: `Bearer ${token}` } : {}; } async function apiFetch(url: string, options: RequestInit = {}): Promise { const res = await fetch(url, { ...options, headers: { ...getAuthHeaders(), ...options.headers, }, }); if (!res.ok) { const errorData = await res.json().catch(() => ({})); throw new Error(errorData.error || `Request failed: ${res.status}`); } return res.json() as Promise; } export function useGetWeeklyReports(clientId: number) { return useQuery({ queryKey: ["weeklyReports", clientId], queryFn: () => apiFetch(`/api/clients/${clientId}/weekly-reports`), enabled: !!clientId, }); } export function useCreateWeeklyReport(clientId: number) { const queryClient = useQueryClient(); return useMutation({ mutationFn: async (file: File) => { const formData = new FormData(); formData.append("file", file); formData.append("report", file); const token = localStorage.getItem("teamtasker_token"); const res = await fetch(`/api/clients/${clientId}/weekly-reports`, { method: "POST", body: formData, headers: { ...(token ? { Authorization: `Bearer ${token}` } : {}), }, }); if (!res.ok) { const errorData = await res.json().catch(() => ({})); throw new Error(errorData.error || "Failed to upload report"); } return res.json() as Promise; }, onSuccess: () => { queryClient.invalidateQueries({ queryKey: ["weeklyReports", clientId] }); }, }); } export function useDeleteWeeklyReport(clientId: number) { const queryClient = useQueryClient(); return useMutation({ mutationFn: (reportId: number) => apiFetch(`/api/clients/${clientId}/weekly-reports/${reportId}`, { method: "DELETE" }), onSuccess: () => { queryClient.invalidateQueries({ queryKey: ["weeklyReports", clientId] }); }, }); } export function useDownloadWeeklyReport(clientId: number) { return useMutation({ mutationFn: async (reportId: number) => { const data = await apiFetch<{ signedUrl: string }>( `/api/clients/${clientId}/weekly-reports/${reportId}/download` ); return data.signedUrl; }, }); }