import type { PropsWithChildren, ReactElement } from "react";
import { render } from "@testing-library/react";
import type { RenderResult } from "@testing-library/react";
import { QueryClient, QueryClientProvider } from "@tanstack/react-query";

export interface RenderOptions {
  queryClient?: QueryClient;
}

// Wraps the given UI with QueryClientProvider only.
// This helper intentionally omits a TRPCProvider. Adding one would require importing
// AppRouter from @repo/core-api, which violates the tooling→core-composition boundary rule.
// For components that need tRPC in the render tree, the consumer must:
//   1. Wire their own TRPCProvider (from their app's tRPC client setup).
//   2. Pass a client built with createMockTrpcClient as the tRPC client.
export function renderWithProviders(
  ui: ReactElement,
  options: RenderOptions = {},
): RenderResult & { queryClient: QueryClient } {
  const queryClient =
    options.queryClient ??
    new QueryClient({
      defaultOptions: {
        queries: { retry: false },
        mutations: { retry: false },
      },
    });

  const Wrapper = ({ children }: PropsWithChildren) => (
    <QueryClientProvider client={queryClient}>{children}</QueryClientProvider>
  );

  const result = render(ui, { wrapper: Wrapper });
  return Object.assign(result, { queryClient });
}
