// ── Short session code generator ──
// 8-character alphanumeric codes, collision-resistant via Durable Object ID

const CHARS = "abcdefghjkmnpqrstuvwxyz23456789"; // no 0,1,i,l,o

export function createCode(): string {
  let code = "";
  for (let i = 0; i < 8; i++) {
    code += CHARS[randomInt(0, CHARS.length - 1)];
  }
  return code;
}

function randomInt(min: number, max: number): number {
  // Use Web Crypto API for secure randomness (available in CF Workers)
  try {
    const arr = new Uint32Array(1);
    // @ts-expect-error — crypto is available at runtime in CF Workers
    crypto.getRandomValues(arr);
    return min + (arr[0] % (max - min + 1));
  } catch {
    // Fallback (dev environments without crypto)
    return min + Math.floor(Math.random() * (max - min + 1));
  }
}
