import { loadMetoyouMobilePlugin } from '../adapters/capacitor/metoyou-mobile.plugin';
import {
  isCameraCaptureAllowed,
  isVoiceCaptureAllowed,
  shouldPreflightMobileCapturePermissions
} from './mobile-media-permission.rules';
import { detectRuntimePlatform, isCapacitorNativeRuntime } from './platform-detection.rules';

function resolveRuntimePlatform(): ReturnType<typeof detectRuntimePlatform> {
  return detectRuntimePlatform({
    hasElectronApi: false,
    capacitorIsNative: isCapacitorNativeRuntime()
  });
}

/** Request Android/iOS runtime microphone permissions before WebRTC voice capture. */
export async function ensureMobileVoiceCapturePermissions(): Promise<boolean> {
  if (!shouldPreflightMobileCapturePermissions(resolveRuntimePlatform())) {
    return true;
  }

  const plugin = await loadMetoyouMobilePlugin();

  if (!plugin?.requestVoiceCapturePermissions) {
    return true;
  }

  try {
    const result = await plugin.requestVoiceCapturePermissions();

    return isVoiceCaptureAllowed(result);
  } catch {
    return false;
  }
}

/** Request Android/iOS runtime camera permissions before WebRTC camera capture. */
export async function ensureMobileCameraCapturePermissions(): Promise<boolean> {
  if (!shouldPreflightMobileCapturePermissions(resolveRuntimePlatform())) {
    return true;
  }

  const plugin = await loadMetoyouMobilePlugin();

  if (!plugin?.requestCameraCapturePermissions) {
    return true;
  }

  try {
    const result = await plugin.requestCameraCapturePermissions();

    return isCameraCaptureAllowed(result);
  } catch {
    return false;
  }
}
