import {
  MutationCache,
  QueryClient,
  type MutationMeta,
} from "@tanstack/react-query";

import i18n from "../i18n";
import { toastManager } from "../toast/toast-manager";
import { errorMessageKey } from "./error-message";

function mutationErrorMessage(
  error: unknown,
  meta: MutationMeta | undefined,
): string {
  if (meta?.errorMessage) return i18n.t(meta.errorMessage);
  const { key, opts } = errorMessageKey(error);
  return i18n.t(key, opts);
}

/** Builds the app's QueryClient, including the MutationCache that bridges every
 *  mutation to the toast region (catch-all error toast + opt-in success toast).
 *  Shared by main.tsx and tests so the toast wiring stays consistent. */
export function makeQueryClient(): QueryClient {
  return new QueryClient({
    defaultOptions: { queries: { retry: false, refetchOnWindowFocus: false } },
    mutationCache: new MutationCache({
      onError: (error, _vars, _ctx, mutation) => {
        if (mutation.meta?.suppressErrorToast) return;
        toastManager.add({
          type: "error",
          description: mutationErrorMessage(error, mutation.meta),
        });
      },
      onSuccess: (_data, _vars, _ctx, mutation) => {
        if (mutation.meta?.successMessage) {
          toastManager.add({
            type: "success",
            description: i18n.t(mutation.meta.successMessage),
          });
        }
      },
    }),
  });
}
