import { NativeEventEmitter, NativeModules, Platform } from 'react-native';
import type { ConfigType, InitiateKycParams, LoginParams } from './types';

const LINKING_ERROR =
  `The package 'react-native-onramp' 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 Go\n';

const Onramp = NativeModules.OnrampSDK
  ? NativeModules.OnrampSDK
  : new Proxy(
      {},
      {
        get() {
          throw new Error(LINKING_ERROR);
        },
      }
    );

export const startOnrampSDK = (config: ConfigType) => {
  if (!config.appId) {
    throw new TypeError("'appId is missing or null.'");
  }
  return Onramp.startSdk(config);
};

export const startOnrampLogin = (params: LoginParams) => {
  if (!params.appId) {
    throw new TypeError("'appId is missing or null.'");
  }

  return Onramp.startOnrampLogin(params);
};

export const initiateOnrampKyc = (params: InitiateKycParams) => {
  if (!params.appId) {
    throw new TypeError("'appId is missing or null.'");
  }
  if (!params.payload) {
    throw new TypeError("'payload is missing or null.'");
  }
  if (!params.signature) {
    throw new TypeError("'signature is missing or null.'");
  }
  if (!params.customerId) {
    throw new TypeError("'customerId is missing or null.'");
  }
  if (!params.apiKey) {
    throw new TypeError("'apiKey is missing or null.'");
  }

  return Onramp.initiateOnrampKyc(params);
};

export const closeOnrampSDK = () => {
  return Onramp.closeSdk();
};

export const onRampSDKNativeEvent = new NativeEventEmitter(
  NativeModules.OnrampSDK
);
