import { apiGet, apiPost } from "@/app/lib/clientApi"; // add-lead-notifications: client wrapper for the bell and /notifications. Calls only this portal's /api/notifications/**. export interface AdminNotification { id: number; title: string; /** JSON {"code","params"}: rendered in the reader's language. */ message: string | null; type: string; link: string | null; seen: boolean; createDateTime: string; } export interface NotificationPage { items: AdminNotification[]; total: number; } /** `page` is 0-based, as mobile-api is. */ export async function listNotifications(page: number, size: number): Promise { const res = await apiGet>(`/api/notifications?page=${page}&size=${size}`); return { items: res?.items ?? [], total: res?.total ?? 0 }; } export async function getUnreadCount(): Promise { return (await apiGet<{ count: number }>("/api/notifications/unread-count"))?.count ?? 0; } export async function markRead(id: number): Promise { await apiPost(`/api/notifications/${id}/read`); } export async function markAllRead(): Promise { await apiPost("/api/notifications/read-all"); } /** Fired after read state changes outside the bell, so the bell recounts at once instead of on its next poll. */ export const NOTIFICATIONS_CHANGED = "notifications:changed"; type T = (code: string, params?: Record) => string; /** The title and body in the reader's language. The row stores codes; anything unreadable shows no body. */ export function noticeText(item: AdminNotification, t: T): { title: string; body: string } { let body = ""; try { const m = JSON.parse(item.message ?? "") as { code?: unknown; params?: Record }; if (typeof m.code === "string") { const params: Record = {}; for (const [k, v] of Object.entries(m.params ?? {})) { if (typeof v === "string" || typeof v === "number") params[k] = v; } body = t(m.code, params); } } catch { /* not JSON: no body */ } return { title: t(item.title), body }; } /** A link opens only when it is a path on this site (a single leading slash, no backslash tricks). */ export function isSitePath(link: string | null | undefined): link is string { return !!link && link.startsWith("/") && !link.startsWith("//") && !link.includes("\\"); } /** Date and time in the reader's locale (stored as en_US, Intl wants en-US). */ export function noticeTime(iso: string, locale: string): string { try { return new Intl.DateTimeFormat(locale.replace("_", "-"), { dateStyle: "medium", timeStyle: "short" }).format(new Date(iso)); } catch { return iso; } }