// Generates a random alphanumeric code for lobby identification
export function generateLobbyCode(length: number = 4): string {
  const characters = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789';
  let result = '';
  for (let i = 0; i < length; i++) {
    result += characters.charAt(Math.floor(Math.random() * characters.length));
  }
  return result;
}

//  Checks if a generated code is unique in the database
export async function isCodeUnique(
  checkFunction: (code: string) => Promise<boolean>,
  code: string
): Promise<boolean> {
  return await checkFunction(code);
}

// Generates a guaranteed unique code by checking against existing codes
export async function generateUniqueCode(
  length: number = 4,
  checkFunction: (code: string) => Promise<boolean>
): Promise<string> {
  let code = generateLobbyCode(length);
  let isUnique = await checkFunction(code);

  // Keep generating codes until we find a unique one
  // Add a safety counter to prevent infinite loops
  let attempts = 0;
  const maxAttempts = 10;

  while (!isUnique && attempts < maxAttempts) {
    code = generateLobbyCode(length);
    isUnique = await checkFunction(code);
    attempts++;
  }

  if (!isUnique) {
    // If we still don't have a unique code after max attempts,
    // increase the length and try again
    return generateUniqueCode(length + 1, checkFunction);
  }

  return code;
}
