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

interface ApkInstallerNative {
  canRequestInstall(): Promise<boolean>;
  openInstallPermissionSettings(): Promise<void>;
  installApk(url: string): Promise<void>;
}

const native: ApkInstallerNative | undefined = NativeModules.ApkInstaller;

/**
 * In-app APK update via Android PackageInstaller (no Chrome download).
 *
 * Flow:
 *   1. canRequestInstall() — sprawdź czy `REQUEST_INSTALL_PACKAGES` granted.
 *   2. Jeśli false → openInstallPermissionSettings() → user toggle once → wraca.
 *   3. installApk(url) — pobiera APK przez OkHttp (TLS pin via Network Security
 *      Config) → PackageInstaller.Session → Android pokazuje "Install update?"
 *      dialog. User klika Install → restart aplikacji w nowej wersji.
 *
 * iOS / web / debug bez native module → returns false / no-op.
 */
export const apkInstallerAvailable = Platform.OS === 'android' && !!native;

export async function canRequestInstall(): Promise<boolean> {
  if (!native) return false;
  try {
    return await native.canRequestInstall();
  } catch {
    return false;
  }
}

export async function openInstallPermissionSettings(): Promise<void> {
  if (!native) return;
  try {
    await native.openInstallPermissionSettings();
  } catch {
    // user closed Settings — ignore
  }
}

export async function installApk(url: string): Promise<void> {
  if (!native) {
    throw new Error('ApkInstaller native module not available');
  }
  await native.installApk(url);
}
