import { useMutation, useQueryClient } from "@tanstack/react-query";
import { api } from "../lib/apiClient.ts";

export function useUpdateReportTodo (monthId) {
	const qc = useQueryClient();
	return useMutation({
		mutationFn:(data) => api.post(`/reports/todo`, data).then(r => r.data),
		onSuccess:(update) => {
			const reports = qc.getQueryData(['reports', monthId]);
			const newTodo = update.todoItem;
			const newReports = reports.map(report => {
				if(report.id === update.reportId){
					const tmp = report.reportsTodos.filter(r => r.id !== newTodo.id);
					tmp.push(newTodo);
					return {...report,reportsTodos: tmp, statusTodo: update.reportStatusTodo}
				}
				return {...report};
			});
			qc.setQueryData(['reports', monthId], [...newReports]);
		},
	})
}