import {
  isPermissionGranted,
  requestPermission,
  sendNotification,
} from '@tauri-apps/plugin-notification';

import { isTauriRuntime } from './globalShortcut';

// Tracks whether permission has already been requested this session so we
// don't spam the OS prompt. Actual permission state lives in the OS.
let permissionChecked = false;
let permissionGranted = false;

export async function ensureNotificationPermission(): Promise<boolean> {
  if (permissionChecked) return permissionGranted;
  permissionChecked = true;
  if (!isTauriRuntime()) {
    // Web preview / Chrome — Tauri notification plugin not available.
    permissionGranted = false;
    return false;
  }
  try {
    let granted = await isPermissionGranted();
    if (!granted) {
      const result = await requestPermission();
      granted = result === 'granted';
    }
    permissionGranted = granted;
  } catch (err: unknown) {
    permissionGranted = false;
    console.warn('notification permission check failed', err);
  }
  return permissionGranted;
}

export function isAppFocused(): boolean {
  return typeof document !== 'undefined' && !document.hidden && document.hasFocus();
}

interface NotifyOpts {
  title: string;
  body?: string;
  // Force notification even when app is focused. Default: suppress if focused.
  force?: boolean;
}

export async function notify({ title, body, force = false }: NotifyOpts): Promise<void> {
  if (!force && isAppFocused()) return;
  if (!isTauriRuntime()) return;
  const granted = await ensureNotificationPermission();
  if (!granted) return;
  try {
    sendNotification({ title, ...(body ? { body } : {}) });
  } catch (err: unknown) {
    console.error('sendNotification failed', err);
  }
}
