import { computed, ref, shallowRef } from "vue";
import {
  listDataTableExports,
  downloadDataTableExport,
  clearReadyDataTableExports,
} from "../services/dataTableService.js";

const readyExports = shallowRef([]);

function poll() {
  listDataTableExports()
    .then((res) => {
      const data = res?.data ?? [];
      readyExports.value = data.filter(
        (e) => e.status === "ready" && e.downloadUrl,
      );
    })
    .catch(() => {});
}

export function useExportNotifications() {
  const dismissedIds = ref(new Set());
  const clearing = ref(false);

  const visibleReadyExports = computed(() =>
    readyExports.value.filter((e) => !dismissedIds.value.has(e.id)),
  );

  async function startDownload(exportItem) {
    if (!exportItem?.id) return;
    dismissedIds.value = new Set([...dismissedIds.value, exportItem.id]);
    try {
      await downloadDataTableExport(exportItem.id, exportItem.resourceKey);
    } catch (e) {
      console.error("Failed to download export", e);
    }
  }

  function refreshSoon() {
    poll();
  }

  async function clearAllReady() {
    if (clearing.value) return;
    clearing.value = true;
    try {
      await clearReadyDataTableExports();
      dismissedIds.value = new Set();
      await poll();
    } catch (e) {
      console.error("Failed to clear ready exports", e);
    } finally {
      clearing.value = false;
    }
  }

  return {
    visibleReadyExports,
    startDownload,
    refreshSoon,
    clearAllReady,
    clearing,
  };
}
