import * as Crypto from 'expo-crypto'

// 62-char alphanumeric alphabet — same shape as the previous Math.random
// implementation so server-side dedup based on Idempotency-Key keeps the
// same key space. `Crypto.getRandomBytesAsync` is the same primitive
// `oauth.ts` uses to mint the PKCE verifier and the `state` parameter, so
// idempotency-key generation now sources entropy from the platform CSPRNG
// (SecRandomCopyBytes on iOS, /dev/urandom-backed on Android) rather than
// `Math.random()` — the latter is non-cryptographic and sometimes
// predictable enough that an attacker who already has the bearer could
// replay a duplicate POST and have it deduped. The bearer is the actual
// security boundary; this is the principle-of-least-surprise fix.
const ALPHABET = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789'

export async function randomKey(length: number): Promise<string> {
  const bytes = await Crypto.getRandomBytesAsync(length)
  let result = ''
  for (let i = 0; i < length; i++) {
    result += ALPHABET.charAt(bytes[i] % ALPHABET.length)
  }
  return result
}
