// ─── Types ────────────────────────────────────────────────────────────────────

export interface AppNotification {
  id: string;
  type: "budget_exceeded" | "budget_warning";
  title: string;
  message: string;
  alertId: string;
  /** Scope of the alert rule: "global" or a provider name. */
  scope: string;
  /** Actual spend at the time the notification was generated. */
  spend: number;
  /** Configured threshold that was crossed. */
  threshold: number;
  createdAt: string;
  readAt: string | null;
}

// ─── Storage ──────────────────────────────────────────────────────────────────

const NOTIF_KEY = "veylant_notifications";

/** Custom event dispatched whenever notifications are saved, so sibling components can react. */
export const NOTIF_CHANGE_EVENT = "veylant:notifications";

export function loadNotifications(): AppNotification[] {
  try {
    return JSON.parse(localStorage.getItem(NOTIF_KEY) ?? "[]");
  } catch {
    return [];
  }
}

/** Persist notifications (max 100) and broadcast the change event. */
export function saveNotifications(notifs: AppNotification[]): void {
  localStorage.setItem(NOTIF_KEY, JSON.stringify(notifs.slice(0, 100)));
  window.dispatchEvent(new Event(NOTIF_CHANGE_EVENT));
}

export function getUnreadCount(): number {
  return loadNotifications().filter((n) => !n.readAt).length;
}
