import { isPermissionGranted, requestPermission, sendNotification } from "@tauri-apps/plugin-notification";
import { getCurrentWindow } from "@tauri-apps/api/window";

const NOTIFY_STATES = ["done", "wait", "error"];
let lastBySurface: Record<string, string> = {};

/// Fire a native notification for a status change when the window is unfocused.
export async function maybeNotify(surfaceId: string, agent: string, workspace: string, state: string): Promise<void> {
  if (!NOTIFY_STATES.includes(state)) return;
  if (lastBySurface[surfaceId] === state) return; // dedup repeats
  lastBySurface[surfaceId] = state;

  const focused = await getCurrentWindow().isFocused().catch(() => true);
  if (focused) return;

  let granted = await isPermissionGranted();
  if (!granted) granted = (await requestPermission()) === "granted";
  if (!granted) return;

  sendNotification({ title: `${workspace} · ${agent}`, body: `${state}` });
}
