import { NativeEventEmitter, Platform } from 'react-native';
import NativeFreshdesk from './NativeFreshdesk';
import type { Spec } from './NativeFreshdesk';

/**
 * NativeFreshdesk is the codegen spec's default export. It is `null` when the
 * native module is not installed (TurboModuleRegistry.get, not getEnforcing).
 * We substitute a no-op so JS-only environments (tests, missing pod install)
 * degrade gracefully instead of throwing at import.
 */
const noOpModule: Spec = {
  initialize: () => Promise.reject(new Error('Freshdesk native module not available')),
  openSupport: () => Promise.reject(new Error('Freshdesk native module not available')),
  openKnowledgeBase: () => Promise.reject(new Error('Freshdesk native module not available')),
  openTopic: () => Promise.reject(new Error('Freshdesk native module not available')),
  getUnreadCount: () => Promise.resolve(0),
  trackEvent: () => Promise.resolve(),
  setUserProperties: () => Promise.resolve(),
  setTicketProperties: () => Promise.resolve(),
  authenticateAndUpdate: () => Promise.resolve(),
  resetUser: () =>
    Promise.resolve({ success: false, message: '', error: 'Native module not available' }),
  dismiss: () => Promise.resolve(),
  setLinkHandlerEnabled: () => Promise.resolve(),
  getSDKVersion: () => Promise.resolve('unknown'),
  getUser: () => Promise.resolve('{}'),
  setContentConfiguration: () => Promise.resolve(),
  enableDebugLogs: () => Promise.resolve(),
  runDiagnostics: () =>
    Promise.resolve({
      platform: Platform.OS,
      overallStatus: 'fail',
      checks: [
        {
          id: 'runtime.nativeModule',
          status: 'fail',
          details: 'Freshdesk native module not available',
          fixHint:
            'Install @freshworks/react-native-freshdesk-sdk, run pod install (iOS) or rebuild Android, then restart Metro.',
        },
      ],
      prettyPrinted: '',
    }),
  addListener: () => {},
  removeListeners: () => {},
};

export const isNativeModuleAvailable: boolean = NativeFreshdesk != null;

if (!isNativeModuleAvailable) {
  console.warn(
    'FreshdeskReactNative native module not found. ' +
      'Make sure the library is properly linked. ' +
      'Falling back to no-op implementation.'
  );
}

export const nativeModule: Spec = NativeFreshdesk ?? noOpModule;

interface NativeModuleEventShim {
  addListener: (eventType: string) => void;
  removeListeners: (count: number) => void;
}

export const eventEmitter: NativeEventEmitter | null = isNativeModuleAvailable
  ? new NativeEventEmitter(nativeModule as unknown as NativeModuleEventShim)
  : null;

export const isSupported: boolean = Platform.OS === 'ios' || Platform.OS === 'android';
