export type DocuSignFunctionError = {
  code?: string;
  message: string;
  consentUrl?: string;
};

export async function extractDocuSignFunctionError(error: unknown): Promise<DocuSignFunctionError> {
  let message = error instanceof Error ? error.message : "An unexpected DocuSign error occurred.";
  let code: string | undefined;
  let consentUrl: string | undefined;

  if (typeof error === "object" && error !== null && "context" in error) {
    const response = (error as { context?: unknown }).context;

    if (response instanceof Response) {
      try {
        const payload = await response.clone().json();
        message = payload?.error || message;
        code = payload?.code;
        consentUrl = payload?.consent_url;
      } catch {
        // Ignore non-JSON bodies.
      }
    }
  }

  if (!code && typeof message === "string" && message.includes("consent_required")) {
    code = "consent_required";
  }

  return {
    code,
    message,
    consentUrl,
  };
}