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

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

vi.mock("@/shared/ui/ToastProvider.jsx", () => ({
    useToast: () => ({ showToast: vi.fn() }),
}));

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

test("coin seller ledger shows sub seller transfer type and filter option", () => {
    vi.mocked(usePaginatedQuery).mockReturnValue(queryFixture([subSellerTransferEntry()]));

    render(<CoinSellerLedgerTable />);

    expect(screen.getByText("向子币商转账")).toBeInTheDocument();
    expect(screen.getByText("Parent seller")).toBeInTheDocument();
    expect(screen.getByText("Child seller")).toBeInTheDocument();
    expect(screen.getByText("-80")).toBeInTheDocument();

    fireEvent.click(screen.getAllByRole("button", { name: /流水类型/ })[0]);

    expect(screen.getAllByText("向子币商转账").length).toBeGreaterThanOrEqual(2);
});

function queryFixture(items) {
    return {
        data: { items, page: 1, pageSize: 50, total: items.length },
        error: null,
        loading: false,
        reload: vi.fn(),
    };
}

function subSellerTransferEntry() {
    return {
        amount: 80,
        availableDelta: -80,
        bizType: "coin_seller_sub_transfer",
        commandId: "cmd-sub-transfer",
        counterpartyUserId: "5001",
        createdAtMs: 1760000000000,
        direction: "expense",
        entryId: 991,
        ledgerType: "sub_seller_transfer",
        metadata: { child_user_id: 5001, parent_user_id: 3001 },
        receiver: { displayUserId: "5001", userId: "5001", username: "Child seller" },
        seller: { displayUserId: "3001", userId: "3001", username: "Parent seller" },
        sellerBalanceAfter: 920,
        transactionId: "tx-sub-transfer",
    };
}
