const DEFAULT_ERROR_MESSAGE = 'Default error';

const isRecord = (value: unknown): value is Record<string, unknown> => {
  return typeof value === 'object' && value !== null;
};

const getStringField = (
  obj: Record<string, unknown>,
  key: string,
): string | undefined => {
  const value = obj[key];
  return typeof value === 'string' && value.trim() ? value : undefined;
};

export const parseUnknownError = (
  error: unknown,
  fallback = DEFAULT_ERROR_MESSAGE,
): string => {
  if (typeof error === 'string') {
    return error.trim() || fallback;
  }

  if (error instanceof Error) {
    return error.message.trim() || fallback;
  }

  if (isRecord(error)) {
    return (
      getStringField(error, 'msg') ??
      getStringField(error, 'message') ??
      fallback
    );
  }

  return fallback;
};
