import { useMutation, useQueryClient } from "@tanstack/react-query"; import { supabase } from "@/auth/supabase"; /** * Hook genérico para actualizar una tabla y guardar respaldo en historico_cambios * * @param tableName Nombre de la tabla a actualizar * @param idKey Campo que se usa para hacer eq (por defecto 'id') */ export function useSupabaseUpdateWithHistory>( tableName: string, idKey: keyof T = "id" as keyof T ) { const qc = useQueryClient(); // Generar diferencias tipo JSON Patch function generateDiff(oldData: T, newData: Partial) { const changes: any[] = []; for (const key of Object.keys(newData)) { const oldValue = (oldData as any)[key]; const newValue = (newData as any)[key]; if (newValue !== undefined && newValue !== oldValue) { changes.push({ op: "replace", path: `/${key}`, from: oldValue, value: newValue, }); } } return changes; } const mutation = useMutation({ mutationFn: async ({ oldData, newData, }: { oldData: T; newData: Partial; }) => { const diff = generateDiff(oldData, newData); if (diff.length > 0) { const { error: backupError } = await supabase .from("historico_cambios") .insert({ id_plan_estudios: oldData.id ?? null, // ajusta si es otra tabla tabla_afectada: tableName, json_cambios: diff, created_at: new Date().toISOString(), }); if (backupError) throw backupError; } const { error } = await supabase .from(tableName) .update(newData) .eq(idKey as string, oldData[idKey]); if (error) throw error; }, }); return { mutation }; }