import { useTranslations } from "next-intl";
import { ApiClientError } from "@/lib/api/client";

/**
 * Returns a resolver that turns any caught error into a localized, user-facing
 * message using the "errors" namespace. Known ApiClientError codes map to their
 * translated message; otherwise the provided fallback is used, then a generic
 * localized message. Never surfaces the raw (English) backend message.
 *
 *   const apiError = useApiError();
 *   onError: (err) => notify.error(apiError(err))
 */
export function useApiError() {
  const t = useTranslations("errors");
  return (err: unknown, fallback?: string): string => {
    const code =
      err instanceof ApiClientError
        ? err.code
        : typeof err === "object" && err !== null && "code" in err
          ? String((err as { code: unknown }).code)
          : undefined;
    if (code && t.has(code)) {
      return t(code);
    }
    return fallback ?? t("generic");
  };
}
