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

/** Global state so all consumers see the same list (e.g. header and any future use). */
const readyExports = shallowRef([]);

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

/**
 * Composable for header (or elsewhere) to show "download ready" notifications.
 * Calls GET /api/datatables/exports on demand; exposes visibleReadyExports (completed with downloadUrl, minus dismissed).
 * Call startDownload(exportItem) when user clicks Download; opens URL and dismisses from list.
 */
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) {
      // If download fails, we keep it dismissed for now; errors are visible in the network tab.
      // Optionally we could re-add the id to visible list here.
      // eslint-disable-next-line no-console
      console.error("Failed to download export", e);
    }
  }

  /** Call when the user opens the dropdown to refresh the list once. */
  function refreshSoon() {
    poll();
  }

  /** Clear all ready exports for the current user. */
  async function clearAllReady() {
    if (clearing.value) return;
    clearing.value = true;
    try {
      await clearReadyDataTableExports();
      dismissedIds.value = new Set();
      await poll();
    } catch (e) {
      // eslint-disable-next-line no-console
      console.error("Failed to clear ready exports", e);
    } finally {
      clearing.value = false;
    }
  }

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