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

const LINKING_ERROR =
  `The package '@chicoai/chico-rn-sdk' 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 ChicoRnSdk = NativeModules.ChicoRnSdk
  ? NativeModules.ChicoRnSdk
  : new Proxy(
      {},
      {
        get() {
          throw new Error(LINKING_ERROR);
        },
      }
    );

function useChicoLogger(client: string, token: string) {
  useEffect(() => {
    if (!token || !client) {
      return;
    }
    ChicoRnSdk.logDataOnChico(client, token, process.env.NODE_ENV).then(
      (result: boolean) => {
        if (!result) {
          console.warn('Chico Logger failed to log mobile metadata');
        }
      }
    );
  }, [client, token]);
}

export default useChicoLogger;
