import { NativeModules, Platform } from 'react-native';

const LINKING_ERROR =
  `The package 'react-native-inapp-update' doesn't seem to be linked. Make sure: \n\n` +
  Platform.select({ ios: "- You have run 'pod install'\n", default: '' }) +
  '- You rebuilt the app after installing the package\n' +
  '- You are not using Expo managed workflow\n';

const InappUpdate = NativeModules.InappUpdate
  ? NativeModules.InappUpdate
  : new Proxy(
      {},
      {
        get() {
          throw new Error(LINKING_ERROR);
        },
      }
    );
//
type appUpdateType = 'IMMEDIATE' | 'FLEXIBLE';
/**
 *@returns {Promise<string>}
 */
export function checkisUpdateAvailable(): Promise<string> {
  return InappUpdate.checkUpdateStatus();
}

/**
 * @param {appUpdateType} appUpdateType
 * @param {string} clientVersionStalenessDays
 * @returns {Promise<string>}
 *
 */
export function startUpdate(
  appUpdateType: appUpdateType,
  clientVersionStalenessDays?: number
): Promise<string> {
  return InappUpdate.checkAppUpdate(
    appUpdateType === 'FLEXIBLE' ? 0 : 1,
    !!clientVersionStalenessDays ? clientVersionStalenessDays : 0
  );
}

/**
 * @return {promise<string>}
 */
export function onCompleteUpdate(): Promise<string> {
  return InappUpdate.completeUpdate();
}
