import { render, screen, waitFor } from "@testing-library/react";
import userEvent from "@testing-library/user-event";
import { QueryClient, QueryClientProvider } from "@tanstack/react-query";
import { describe, expect, it, vi } from "vitest";
import { AccountSearch } from "./AccountSearch";

const accounts = vi.fn();
vi.mock("@/lib/api", async () => {
    const actual = await vi.importActual<typeof import("@/lib/api")>("@/lib/api");
    return {
        ...actual,
        api: { ...actual.api, staff: { ...actual.api.staff, accounts: (q?: string) => accounts(q) } },
    };
});

function wrap(ui: React.ReactNode) {
    const client = new QueryClient({ defaultOptions: { queries: { retry: false } } });
    return render(<QueryClientProvider client={client}>{ui}</QueryClientProvider>);
}

describe("AccountSearch", () => {
    it("finds an account by instance UUID, which is often all a support email has", async () => {
        const uuid = "6a0fe3f0-49d2-4aa1-967c-a3094b200b5d";
        accounts.mockResolvedValue([
            {
                account_id: "a1",
                name: "Acme",
                billing_email: "ops@acme.example",
                status: "active",
                created_at: "2026-01-01T00:00:00Z",
            },
        ]);

        wrap(<AccountSearch />);
        await userEvent.type(screen.getByLabelText(/search/i), uuid);

        await waitFor(() => expect(accounts).toHaveBeenCalledWith(uuid));
        expect(await screen.findByRole("link", { name: /acme/i })).toHaveAttribute(
            "href",
            "/staff/accounts/a1",
        );
    });
});
