// src/lib/auth/username-policy.ts — username validation for the Better Auth
// `username` plugin. Providing a custom `usernameValidator` REPLACES the plugin
// default (`/^[a-zA-Z0-9_.]+$/`, confirmed in
// node_modules/better-auth/dist/plugins/username/index.mjs), so we re-create that
// allowed-character rule here and additionally reject a small reserved-handle
// list. Length (3–30) is enforced separately by the plugin's
// min/maxUsernameLength options — not re-checked here.
export const MIN_USERNAME_LENGTH = 3;
export const MAX_USERNAME_LENGTH = 30;

// Plugin default allowed-character set: letters, digits, underscore, dot.
const ALLOWED_USERNAME = /^[a-zA-Z0-9_.]+$/;

// Handles nobody may claim — system / route names that would be confusing or
// abusable as a public identifier. Compared case-insensitively.
const RESERVED_USERNAMES = new Set([
  "admin",
  "administrator",
  "superadmin",
  "root",
  "support",
  "help",
  "system",
  "moderator",
  "owner",
  "staff",
  "member",
  "api",
  "auth",
  "billing",
  "settings",
  "seoinsight",
]);

// Default validationOrder is "pre-normalization", so this receives the RAW input
// (before lowercasing). Lowercase only for the reserved-name comparison.
export function isValidUsername(username: string): boolean {
  if (!ALLOWED_USERNAME.test(username)) return false;
  if (RESERVED_USERNAMES.has(username.toLowerCase())) return false;
  return true;
}
