import { fireEvent, render, screen } from "@testing-library/react";
import { afterEach, expect, test, vi } from "vitest";
import { GiftRecordTable } from "@/features/operations/components/GiftRecordTable.jsx";
import { usePaginatedQuery } from "@/shared/hooks/usePaginatedQuery.js";

vi.mock("@/shared/hooks/usePaginatedQuery.js", () => ({
    usePaginatedQuery: vi.fn(),
}));

afterEach(() => {
    vi.clearAllMocks();
});

test("gift record table uses public user identities and keeps gift facts compact", () => {
    vi.mocked(usePaginatedQuery).mockReturnValue({
        data: {
            items: [
                {
                    createdAtMs: 1770000000000,
                    gift: { coverUrl: "https://cdn.example/rose.webp", giftId: "rose", name: "玫瑰" },
                    giftCount: 3,
                    giftValue: 300,
                    receiver: { displayUserId: "202", userId: "2002", username: "收礼人" },
                    roomId: "room-9",
                    scene: "room",
                    sender: {
                        defaultDisplayUserId: "101",
                        displayUserId: "888888",
                        prettyDisplayUserId: "888888",
                        prettyId: "pretty-1",
                        userId: "1001",
                        username: "送礼人",
                    },
                    transactionId: "wallet-gift-1",
                    unitValue: 100,
                },
            ],
            page: 1,
            pageSize: 30,
            total: 1,
        },
        error: null,
        loading: false,
        reload: vi.fn(),
    });

    render(<GiftRecordTable />);

    expect(screen.getByText("1")).toBeInTheDocument();
    expect(screen.getAllByText("送礼人").length).toBeGreaterThanOrEqual(2);
    expect(screen.getAllByText("收礼人").length).toBeGreaterThanOrEqual(2);
    expect(screen.getByText("玫瑰")).toBeInTheDocument();
    expect(screen.getByText("× 3")).toBeInTheDocument();
    expect(screen.getByText("300")).toBeInTheDocument();
    expect(screen.getByText("房间")).toBeInTheDocument();
    expect(screen.getByText("room-9")).toBeInTheDocument();
    expect(screen.getByText("已加载 1 条 · 共 1 条")).toBeInTheDocument();

    fireEvent.click(screen.getByRole("button", { name: "送礼人" }));
    fireEvent.change(screen.getByPlaceholderText("输入短 ID"), { target: { value: "888888" } });
    fireEvent.click(screen.getByRole("button", { name: "搜索" }));

    expect(usePaginatedQuery).toHaveBeenLastCalledWith(
        expect.objectContaining({
            filters: expect.objectContaining({ sender_display_user_id: "888888" }),
            page: 1,
        }),
    );
});
