"use client";

const RUN_DUE_COOLDOWN_MS = 60 * 1000;
const lastRunByScope = new Map<string, number>();
const pendingRunByScope = new Map<string, Promise<void>>();

export function triggerDueAutomations(teamId: string | null) {
  if (typeof window === "undefined") {
    return Promise.resolve();
  }

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

  const lastRun = lastRunByScope.get(scopeKey) || 0;
  if (Date.now() - lastRun < RUN_DUE_COOLDOWN_MS) {
    return Promise.resolve();
  }

  const promise = fetch("/api/automations/run-due", {
    method: "POST",
    headers: {
      "Content-Type": "application/json",
    },
    body: JSON.stringify({ teamId }),
  })
    .then(() => {})
    .catch(() => {
      // Best-effort foreground scheduler. The next visible load will retry.
    })
    .finally(() => {
      lastRunByScope.set(scopeKey, Date.now());
      pendingRunByScope.delete(scopeKey);
    });

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