import { isCapacitorNativeRuntime } from '../../logic/platform-detection.rules';

import type { MobileCapturePermissionResult } from '../../logic/mobile-media-permission.rules';

export interface MetoyouMobilePlugin {
  requestVoiceCapturePermissions(): Promise<MobileCapturePermissionResult>;
  requestCameraCapturePermissions(): Promise<MobileCapturePermissionResult>;
  setSpeakerphoneEnabled(options: { enabled: boolean }): Promise<void>;
  startVoiceForegroundService(): Promise<void>;
  stopVoiceForegroundService(): Promise<void>;
  enterNativePictureInPicture(): Promise<{ supported: boolean }>;
  exitNativePictureInPicture(): Promise<void>;
  startCallKitSession(options: { callId: string; displayName: string }): Promise<{ supported: boolean }>;
  endCallKitSession(options: { callId: string }): Promise<void>;
  isRemotePushConfigured(): Promise<{ configured: boolean }>;
}

let metoyouMobilePluginPromise: Promise<MetoyouMobilePlugin | null> | null = null;

/** Lazily register the MetoyouMobile Capacitor plugin on native shells only. */
export async function loadMetoyouMobilePlugin(): Promise<MetoyouMobilePlugin | null> {
  if (typeof window === 'undefined' || !isCapacitorNativeRuntime()) {
    return null;
  }

  if (!metoyouMobilePluginPromise) {
    metoyouMobilePluginPromise = import('@capacitor/core')
      .then(({ registerPlugin }) => registerPlugin<MetoyouMobilePlugin>('MetoyouMobile'))
      .catch(() => null);
  }

  return metoyouMobilePluginPromise;
}
