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

interface AntiTamperNative {
  getSignatureHash(): Promise<string>;
}

const native: AntiTamperNative | undefined = NativeModules.AntiTamper;

let cached: string | null | undefined;

/**
 * Returns the SHA-256 (hex, lowercase) of this APK's signing certificate.
 * Sent in `X-App-Signature` header on every request so the backend can
 * reject re-packaged builds (different keystore → different hash).
 *
 * Caches the value for the process lifetime — the signature can't change
 * without reinstalling the APK, and the native call hits PackageManager
 * synchronously so a single fetch per session is plenty.
 *
 * Returns null on iOS (no implementation), on bridge errors, or in dev
 * environments where the module isn't linked. Caller should treat null
 * as "no signature available" — the backend will accept it only if
 * ALLOWED_APP_SIG_HASH is unset (dev mode).
 */
export async function getAppSignatureHash(): Promise<string | null> {
  if (cached !== undefined) return cached;
  if (Platform.OS !== 'android' || !native) {
    cached = null;
    return null;
  }
  try {
    const hash = await native.getSignatureHash();
    cached = hash.toLowerCase();
    return cached;
  } catch {
    cached = null;
    return null;
  }
}
