// eslint-disable-next-line no-restricted-imports -- this is the wrapper itself
import { useToast as useBaseToast } from "@tailor-platform/app-shell";
import type { CombinedError } from "urql";

// Extract a human-readable error message from a urql CombinedError.
// Backend resolver errors are wrapped as "rpc error: code = ... desc = Error: <message>"
// inside extensions.attr.error. This function extracts <message> when available.
function getErrorMessage(error: CombinedError): string {
  const gqlError = error.graphQLErrors[0];
  const attrError = (gqlError?.extensions as Record<string, Record<string, string>> | undefined)
    ?.attr?.error;
  if (attrError) {
    const match = /desc = (?:\w+: )?(.+?)(?:\n|$)/.exec(attrError);
    if (match) return match[1];
  }
  return error.message;
}

// Wraps useToast so that toast.error() accepts a CombinedError directly
// and automatically extracts the human-readable message.
export function useToast() {
  const toast = useBaseToast();
  return {
    ...toast,
    error: (error: string | CombinedError) => {
      const message = typeof error === "string" ? error : getErrorMessage(error);
      toast.error(message);
    },
  };
}
