import { apiGet, apiPost } from "@/app/lib/clientApi"; import type { AdminNotification, BroadcastRequest, BroadcastResult } from "@/app/lib/types"; // Client-side wrapper for the admin notification bell + /notifications compose page. Calls only // the portal's own /api/notifications/** route handlers (Spec B §7.1) — never solvway-mobile-api // directly. export interface NotificationListParams { /** 1-based, matching this portal's other list pages; translated to 0-based at the boundary. */ page: number; pageSize: number; } export interface NotificationListResult { items: AdminNotification[]; total: number; } /** * Builds the query string for GET /api/notifications. `page` is 1-based here (this portal's * list-page convention) but mobile-api's `/api/admin/notifications` (and services-system beneath * it) is 0-based, so it is translated at the boundary. */ export function buildNotificationsQuery(params: NotificationListParams): string { const qs = new URLSearchParams(); qs.set("page", String(Math.max(0, params.page - 1))); qs.set("size", String(params.pageSize)); return qs.toString(); } /** * Normalizes the raw inbox response into `{items, total}`. Upstream /notification/inbox returns a * plain array; the paged shapes are accepted defensively, defaulting to an empty page. */ export function normalizeNotificationList(raw: unknown): NotificationListResult { if (Array.isArray(raw)) return { items: raw as AdminNotification[], total: raw.length }; if (!raw || typeof raw !== "object") return { items: [], total: 0 }; const obj = raw as Record; const items: AdminNotification[] = Array.isArray(obj.content) ? (obj.content as AdminNotification[]) : Array.isArray(obj.items) ? (obj.items as AdminNotification[]) : []; const total = typeof obj.totalElements === "number" ? obj.totalElements : typeof obj.total === "number" ? obj.total : items.length; return { items, total }; } export async function listNotifications(params: NotificationListParams): Promise { const raw = await apiGet(`/api/notifications?${buildNotificationsQuery(params)}`); return normalizeNotificationList(raw); } export async function getUnreadCount(): Promise { const result = await apiGet<{ count: number }>("/api/notifications/unread-count"); return result.count; } export async function markRead(id: number): Promise { await apiPost<{ updated: number }>(`/api/notifications/${id}/read`); } export async function markAllRead(): Promise { await apiPost<{ marked: number }>("/api/notifications/read-all"); } export async function broadcast(payload: BroadcastRequest): Promise { return apiPost("/api/notifications", payload); }