// Copyright © 2022 Olo Inc. All rights reserved.
// This software is made available under the Olo Pay SDK License (See LICENSE.md file)
import { NativeModules, Platform } from 'react-native';
import type { Spec } from '../NativeOlopaysdkReactNative';

const LINKING_ERROR =
  `The package '@olo/pay-react-native' 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';

// Try to use the TurboModule if available (New Architecture)
// Fall back to NativeModules if not (Old Architecture)
// @ts-ignore
const isTurboModuleEnabled = global.__turboModuleProxy != null;

let OlopaysdkReactNative: Spec;

if (isTurboModuleEnabled) {
  try {
    // Dynamic import to avoid errors in Old Architecture
    const NativeModule = require('../NativeOlopaysdkReactNative').default;
    OlopaysdkReactNative = NativeModule;
  } catch (e) {
    // If TurboModule import fails, fall back to NativeModules
    OlopaysdkReactNative = NativeModules.OlopaysdkReactNative
      ? NativeModules.OlopaysdkReactNative
      : new Proxy(
          {},
          {
            get() {
              throw new Error(LINKING_ERROR);
            },
          }
        );
  }
} else {
  OlopaysdkReactNative = NativeModules.OlopaysdkReactNative
    ? NativeModules.OlopaysdkReactNative
    : new Proxy(
        {},
        {
          get() {
            throw new Error(LINKING_ERROR);
          },
        }
      );
}

export default function useOloPayNativeModule(): Spec {
  return OlopaysdkReactNative;
}
