import { ref, onUnmounted } from "vue";
import { getImportStatus } from "src/api/importStatus";

const POLL_INTERVAL_MS = 10000;
const MAX_ATTEMPTS     = 10; // 5 minutes

export function useImportPoller() {
  const polling   = ref(false);
  let   timerId   = null;
  let   attempts  = 0;

  const stop = () => {
    if (timerId !== null) {
      clearInterval(timerId);
      timerId  = null;
      attempts = 0;
    }
    polling.value = false;
  };

  onUnmounted(stop);

  const start = (importId, { onComplete, onError, onTimeout }) => {
    stop();
    polling.value = true;
    attempts      = 0;

    timerId = setInterval(async () => {
      attempts++;

      if (attempts > MAX_ATTEMPTS) {
        stop();
        onTimeout?.();
        return;
      }

      try {
        const result = await getImportStatus(importId);

        if (result.status === "completed") {
          stop();
          onComplete?.(result.stats);
        } else if (result.status === "failed") {
          stop();
          onError?.(result.message ?? "unknown error");
        }
        // 'pending' | 'processing' → keep polling
      } catch {
        stop();
        onError?.("request_failed");
      }
    }, POLL_INTERVAL_MS);
  };

  return { polling, start, stop };
}
