/* eslint-disable @typescript-eslint/no-explicit-any */
import { UNNativePromiseReject, UNVPError, UNVPErrorType } from './types';

export const isUNVPError = (error: any): error is UNVPError => {
  return 'code' in error &&
    'description' in error &&
    'type' in error &&
    isUNVPErrorType(error.type) &&
    'correlationId' in error;
};

const isUNVPErrorType = (type: any): type is UNVPErrorType => {
  return Object.values(UNVPErrorType).includes(type);
};

export const isUNNativePromiseReject = (error: any): error is UNNativePromiseReject => {
  return 'code' in error && 'message' in error;
};

export const promiseRejectToUNVPErrorType = (error: any): UNVPErrorType | null => {
  // validate the shape of a promise reject we get from iOS/Android native
  if (!isUNNativePromiseReject(error)) {
    return null;
  }
  const parsedError = JSON.parse(error.message);
  // validate the shape of an error we get from VDE SDK
  if (!isUNVPError(parsedError)) {
    return null;
  }
  return parsedError.type;
};
