import { ApiError, apiGet, apiPost } from "@/app/lib/clientApi"; import type { AdminMemberRank, AdminMemberStatus } from "@/app/lib/types"; // Client over the BFF routes app/api/admin/member-messages/** (BO_MEMBER_MESSAGES gated upstream). // Shapes are the Wire Contract of the member-messaging plan; mobile-api passes them through. export type ConversationType = "M" | "S" | "B"; export interface ConversationView { uuid: string; type: ConversationType; counterpartCode: string | null; counterpartName: string | null; relationship: "SPONSOR" | "UPLINE" | "DOWNLINE" | "SUPPORT" | "BROADCAST" | null; level: number | null; subject: string | null; lastMessageAt: string; lastMessagePreview: string; unread: boolean; canSend: boolean; } export interface MessageView { uuid: string; senderType: "M" | "A"; senderCode: string | null; // admin username for senderType "A" (admin reader), member code for "M" mine: boolean; body: string | null; imageCount: number; createdAt: string; /** Monotonic message id: order by this, not createdAt. */ seq: number; } export interface PageResult { items: T[]; page: number; size: number; total: number } export interface MessagePage { items: MessageView[]; hasMore: boolean } export interface SendResult { conversationUuid: string; message: MessageView } export type BroadcastTarget = | { kind: "ALL" } | { kind: "FILTER"; rank?: AdminMemberRank; nationality?: string; status?: AdminMemberStatus } | { kind: "LIST"; codes: string[] } | { kind: "DOWNLINE"; code: string; includeSelf: boolean }; export interface BroadcastSummary { broadcastUuid: string; subject: string | null; sentAt: string; sentBy: string | null; recipients: number; read: number; } export interface BroadcastRecipient { memberCode: string; memberName: string | null; read: boolean; conversationUuid: string; } export type InboxTab = "ALL" | "UNREAD" | "S" | "B"; export const MAX_BODY = 2000; export const MAX_IMAGES = 4; export const MAX_IMAGE_BYTES = 5 * 1024 * 1024; export const IMAGE_TYPES = ["image/jpeg", "image/png"]; // Reasons the BFF relay derives from mobile-api's {"message": reason}; each has a MsgErr_ i18n key. const ERROR_CODES = ["NOT_IN_NETWORK", "MESSAGE_INVALID", "MESSAGE_IMAGE_NOT_OWNED", "MESSAGE_COMMIT_FAILED", "MESSAGE_UPLOAD_FAILED", "EMPTY_TARGET"]; /** Friendly copy for a failed call: known reason -> its translated message, else the error text, else the fallback key. */ export function messageErrorText(e: unknown, t: (key: string) => string, fallbackKey = "MsgSendFailed"): string { const data = e instanceof ApiError ? (e.data as { code?: unknown } | undefined) : undefined; const raw = e instanceof Error ? e.message : ""; const code = ERROR_CODES.find((c) => c === data?.code) ?? ERROR_CODES.find((c) => raw.includes(c)); return code ? t(`MsgErr_${code}`) : raw || t(fallbackKey); } const BASE = "/api/admin/member-messages"; const id = encodeURIComponent; /** Inbox page. `page` is 1-based here, 0-based on the wire. ALL sends no type (server forces S,B). */ export function listAdminConversations(f: { tab: InboxTab; q: string; sortBy?: string; sortDir?: "asc" | "desc" }, page: number, size: number) { const p = new URLSearchParams(); if (f.tab === "UNREAD") p.set("unreadOnly", "true"); if (f.tab === "S" || f.tab === "B") p.set("types", f.tab); if (f.q) p.set("q", f.q); if (f.sortBy) { p.set("sortBy", f.sortBy); if (f.sortDir) p.set("sortDir", f.sortDir); } p.set("page", String(Math.max(0, page - 1))); p.set("size", String(size)); return apiGet>(`${BASE}?${p.toString()}`); } export const getAdminUnreadCount = () => apiGet<{ count: number }>(`${BASE}/unread-count`); export const getAdminConversationByMember = (member: string) => apiGet(`${BASE}/by-key?member=${id(member)}`); export const getAdminConversation = (uuid: string) => apiGet(`${BASE}/${id(uuid)}`); /** Newest first; pass the oldest loaded message uuid as `before` to page back. */ export function listAdminMessages(uuid: string, before?: string, size = 30) { const p = new URLSearchParams(); if (before) p.set("before", before); p.set("size", String(size)); return apiGet(`${BASE}/${id(uuid)}/messages?${p.toString()}`); } export const sendAdminMessage = (uuid: string, body: string, imageRefs: string[]) => apiPost(`${BASE}/${id(uuid)}/messages`, { body, imageRefs }); export const markAdminRead = (uuid: string) => apiPost<{ updated: boolean }>(`${BASE}/${id(uuid)}/read`); export const startAdminConversation = (memberCode: string, body: string, imageRefs: string[]) => apiPost(`${BASE}/start`, { memberCode, body, imageRefs }); export const adminMessageImageUrl = (uuid: string, messageUuid: string, index: number) => `${BASE}/${id(uuid)}/messages/${id(messageUuid)}/images/${index}`; export const previewBroadcast = (target: BroadcastTarget) => apiPost<{ count: number }>(`${BASE}/broadcasts/preview`, { target }); export const sendBroadcast = (target: BroadcastTarget, subject: string, body: string, imageRefs: string[]) => apiPost<{ count: number; broadcastUuid: string }>(`${BASE}/broadcasts`, { target, subject, body, imageRefs }); /** One row per broadcast, newest first. `page` is 1-based here, 0-based on the wire. */ export function listAdminBroadcasts(f: { q: string; sortBy?: string; sortDir?: "asc" | "desc" }, page: number, size: number) { const p = new URLSearchParams(); if (f.q) p.set("q", f.q); if (f.sortBy) { p.set("sortBy", f.sortBy); if (f.sortDir) p.set("sortDir", f.sortDir); } p.set("page", String(Math.max(0, page - 1))); p.set("size", String(size)); return apiGet>(`${BASE}/broadcasts?${p.toString()}`); } export const getAdminBroadcast = (uuid: string) => apiGet(`${BASE}/broadcasts/${id(uuid)}`); export function listAdminBroadcastRecipients(uuid: string, f: { unreadOnly: boolean; sortBy?: string; sortDir?: "asc" | "desc" }, page: number, size: number) { const p = new URLSearchParams(); if (f.unreadOnly) p.set("unreadOnly", "true"); p.set("page", String(Math.max(0, page - 1))); p.set("size", String(size)); if (f.sortBy) p.set("sortBy", f.sortBy); if (f.sortDir && f.sortBy) p.set("sortDir", f.sortDir); return apiGet>(`${BASE}/broadcasts/${id(uuid)}/recipients?${p.toString()}`); } /** Client-side pre-check; the server re-validates. */ export function validateImage(file: File): "type" | "size" | null { if (!IMAGE_TYPES.includes(file.type)) return "type"; if (file.size > MAX_IMAGE_BYTES) return "size"; return null; } /** Multipart upload (step 1 of the TWO-STEP flow); apiPost is JSON-only so this uses fetch directly. */ export async function uploadAdminMessageImage(file: File): Promise<{ ref: string }> { const form = new FormData(); form.set("file", file, file.name); const res = await fetch(`${BASE}/images`, { method: "POST", body: form }); const text = await res.text(); let data: unknown; try { data = text ? JSON.parse(text) : undefined; } catch { data = undefined; } if (!res.ok) { if (res.status === 401 && typeof window !== "undefined") window.location.assign("/login"); throw new ApiError((data as { error?: string } | undefined)?.error ?? `Request failed (${res.status})`, res.status, data); } return data as { ref: string }; }