"use client";

const CLEANUP_COOLDOWN_MS = 5 * 60 * 1000;
const lastCleanupByScope = new Map<string, number>();
const pendingCleanupByScope = new Map<string, Promise<void>>();

export function triggerTaskCleanup(teamId: string | null, options: { force?: boolean } = {}) {
  if (typeof window === "undefined") {
    return Promise.resolve();
  }

  const scopeKey = teamId || "personal";
  const pending = pendingCleanupByScope.get(scopeKey);
  if (pending) {
    return pending;
  }

  const lastRun = lastCleanupByScope.get(scopeKey) || 0;
  if (!options.force && Date.now() - lastRun < CLEANUP_COOLDOWN_MS) {
    return Promise.resolve();
  }

  const promise = fetch("/api/tasks/cleanup", {
    method: "POST",
    headers: {
      "Content-Type": "application/json",
    },
    body: JSON.stringify({ teamId }),
  })
    .then(() => {})
    .catch(() => {
      // Best-effort cleanup. The next foreground load will try again.
    })
    .finally(() => {
      lastCleanupByScope.set(scopeKey, Date.now());
      pendingCleanupByScope.delete(scopeKey);
    });

  pendingCleanupByScope.set(scopeKey, promise);
  return promise;
}
