import { describe, it, expect, vi, beforeEach, afterEach } from "vitest"; import { act, render, screen, waitFor } from "@testing-library/react"; import userEvent from "@testing-library/user-event"; import { MessageThreadDrawer, mergeMessages } from "./MessageThreadDrawer"; import { getAdminConversation, listAdminMessages, markAdminRead, sendAdminMessage, type ConversationView, type MessageView, } from "@/app/lib/services/adminMessages"; vi.mock("@/app/lib/services/adminMessages", async (orig) => ({ ...(await orig()), getAdminConversation: vi.fn(), listAdminMessages: vi.fn(), sendAdminMessage: vi.fn(), markAdminRead: vi.fn(), uploadAdminMessageImage: vi.fn(), })); const head: ConversationView = { uuid: "c1", type: "S", counterpartCode: "MY3", counterpartName: "Aisyah", relationship: "SUPPORT", level: null, subject: null, lastMessageAt: "2026-09-30T10:01:00", lastMessagePreview: "hello", unread: true, canSend: true, }; const msg = (uuid: string, body: string, at: string, senderType: "M" | "A" = "M", senderCode = "MY3", imageCount = 0): MessageView => ({ uuid, senderType, senderCode, mine: false, body, imageCount, createdAt: at, seq: Date.parse(at) / 1000 }); const m1 = msg("m1", "hello", "2026-09-30T10:00:00"); const m2 = msg("m2", "new one", "2026-09-30T10:01:00"); beforeEach(() => { vi.mocked(getAdminConversation).mockReset().mockResolvedValue(head); vi.mocked(listAdminMessages).mockReset().mockResolvedValue({ items: [m1], hasMore: false }); vi.mocked(markAdminRead).mockReset().mockResolvedValue({ updated: true }); vi.mocked(sendAdminMessage).mockReset(); }); afterEach(() => { vi.useRealTimers(); Object.defineProperty(document, "visibilityState", { value: "visible", configurable: true }); }); describe("mergeMessages", () => { it("merges by uuid, keeps oldest first and never duplicates", () => { expect(mergeMessages([m1], [m2, m1]).map((m) => m.uuid)).toEqual(["m1", "m2"]); }); }); describe("MessageThreadDrawer", () => { it("shows the thread, the admin username on admin messages, and marks it read on open", async () => { const onChanged = vi.fn(); vi.mocked(listAdminMessages).mockResolvedValue({ items: [msg("m2", "we shipped it", "2026-09-30T10:05:00", "A", "alice"), m1], hasMore: false }); render(); expect(await screen.findByText("hello")).toBeInTheDocument(); expect(screen.getByText(/alice/)).toBeInTheDocument(); await waitFor(() => expect(markAdminRead).toHaveBeenCalledWith("c1")); await waitFor(() => expect(onChanged).toHaveBeenCalled()); }); it("renders bodies as plain text", async () => { vi.mocked(listAdminMessages).mockResolvedValue({ items: [msg("m1", "bold", "2026-09-30T10:00:00")], hasMore: false }); render(); expect(await screen.findByText("bold")).toBeInTheDocument(); expect(document.querySelector("b")).toBeNull(); }); it("polls every 15s while visible, merges a new message once, and stops while hidden", async () => { vi.useFakeTimers(); render(); await act(async () => {}); expect(screen.getByText("hello")).toBeInTheDocument(); expect(markAdminRead).toHaveBeenCalledTimes(1); vi.mocked(listAdminMessages).mockResolvedValue({ items: [m2, m1], hasMore: false }); await act(async () => { await vi.advanceTimersByTimeAsync(15_000); }); expect(screen.getByText("new one")).toBeInTheDocument(); expect(screen.getAllByText("hello")).toHaveLength(1); expect(markAdminRead).toHaveBeenCalledTimes(2); // a member message arrived while open await act(async () => { await vi.advanceTimersByTimeAsync(15_000); }); // same page again: no duplicate expect(screen.getAllByText("new one")).toHaveLength(1); Object.defineProperty(document, "visibilityState", { value: "hidden", configurable: true }); const calls = vi.mocked(listAdminMessages).mock.calls.length; await act(async () => { await vi.advanceTimersByTimeAsync(45_000); }); expect(vi.mocked(listAdminMessages).mock.calls.length).toBe(calls); }); it("sends a reply, appends it once and clears the composer", async () => { vi.mocked(sendAdminMessage).mockResolvedValue(msg("m3", "on it", "2026-09-30T10:09:00", "A", "alice")); const onChanged = vi.fn(); render(); await screen.findByText("hello"); const send = screen.getByRole("button", { name: "Send" }); expect(send).toBeDisabled(); await userEvent.type(screen.getByRole("textbox", { name: "Reply" }), "on it"); expect(screen.getByText("5/2000")).toBeInTheDocument(); await userEvent.click(send); await waitFor(() => expect(sendAdminMessage).toHaveBeenCalledWith("c1", "on it", [])); expect(await screen.findByText("on it", { selector: "p" })).toBeInTheDocument(); expect(screen.getByRole("textbox", { name: "Reply" })).toHaveValue(""); }); it("shows a send failure inline and keeps the draft", async () => { vi.mocked(sendAdminMessage).mockRejectedValue(new Error("Upstream down")); render(); await screen.findByText("hello"); await userEvent.type(screen.getByRole("textbox", { name: "Reply" }), "x"); await userEvent.click(screen.getByRole("button", { name: "Send" })); expect(await screen.findByText("Upstream down")).toBeInTheDocument(); expect(screen.getByRole("textbox", { name: "Reply" })).toHaveValue("x"); }); it("shows friendly copy, not the raw reason, for a known send failure", async () => { vi.mocked(sendAdminMessage).mockRejectedValue(new Error("MESSAGE_COMMIT_FAILED")); render(); await screen.findByText("hello"); await userEvent.type(screen.getByRole("textbox", { name: "Reply" }), "x"); await userEvent.click(screen.getByRole("button", { name: "Send" })); expect(await screen.findByText("The message couldn't be saved. Please try again.")).toBeInTheDocument(); expect(screen.queryByText("MESSAGE_COMMIT_FAILED")).toBeNull(); }); it("loads older messages with the oldest uuid as cursor", async () => { vi.mocked(listAdminMessages) .mockResolvedValueOnce({ items: [m2], hasMore: true }) .mockResolvedValueOnce({ items: [m1], hasMore: false }); render(); await userEvent.click(await screen.findByRole("button", { name: "Load older messages" })); expect(await screen.findByText("hello")).toBeInTheDocument(); expect(listAdminMessages).toHaveBeenLastCalledWith("c1", "m2"); }); }); // babyboo-56-warranty-claims: the composer can open holding a draft (prop initialDraft). describe("MessageThreadDrawer initialDraft", () => { it("puts the draft in the composer and sends nothing", async () => { render(); expect(await screen.findByRole("textbox", { name: "Reply" })).toHaveValue("Warranty claim WC1: "); expect(sendAdminMessage).not.toHaveBeenCalled(); }); });