/**
 * Deterministic base62 referral code from a user ID.
 * Uses the first 10 chars of the ID as a hash, producing a 6-character code.
 * When the hash is exhausted early, the position index is used as padding,
 * making the output deterministic for the same input.
 */
export function encodeReferralCode(userId: string): string {
  const chars = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz";
  let hash = 0;
  for (let i = 0; i < Math.min(userId.length, 10); i++) {
    hash = (hash * 31 + userId.charCodeAt(i)) >>> 0;
  }

  let code = "";
  const originalHash = hash;
  while (code.length < 6) {
    code = chars[hash % 62] + code;
    hash = Math.floor(hash / 62);
    if (hash === 0 && code.length < 6) {
      // Deterministic padding: iteratively hash the original value
      hash = (originalHash * (code.length + 1) * 7) >>> 0;
    }
  }
  return code;
}

/**
 * Find a user by their referral code by iterating all users and
 * re-encoding their IDs until a match is found.
 */
export async function findReferrerByCode(
  users: { id: string }[],
  code: string
): Promise<string | null> {
  for (const u of users) {
    if (encodeReferralCode(u.id) === code) {
      return u.id;
    }
  }
  return null;
}
