import { onMounted, onUnmounted } from "vue";
import type { Ref } from "vue";

export function useAutoSave(
  dirty: Ref<boolean>,
  saving: Ref<boolean>,
  saveFn: () => Promise<void>,
  intervalMs = 5 * 60 * 1000,
): void {
  let timer: ReturnType<typeof setInterval> | null = null;

  onMounted(() => {
    timer = setInterval(async () => {
      if (!dirty.value || saving.value) return;
      await saveFn();
    }, intervalMs);
  });

  onUnmounted(() => {
    if (timer !== null) clearInterval(timer);
  });
}
