export const MIN_USERNAME_LENGTH = 3;
export const MAX_USERNAME_LENGTH = 32;

const USERNAME_PATTERN = /^[a-z][a-z0-9_]*[a-z0-9]$|^[a-z]$/;

const RESERVED_USERNAMES = new Set([
  "admin",
  "administrator",
  "api",
  "auth",
  "billing",
  "dashboard",
  "help",
  "hexahost",
  "login",
  "logout",
  "moderator",
  "null",
  "register",
  "root",
  "settings",
  "support",
  "system",
  "undefined",
  "user",
  "www",
]);

export interface UsernameValidationResult {
  valid: boolean;
  error?: string;
}

export function sanitizeUsername(input: string): string {
  const normalized = input
    .trim()
    .toLowerCase()
    .replace(/[^a-z0-9_]+/g, "_")
    .replace(/_+/g, "_")
    .replace(/^_+|_+$/g, "");

  if (!normalized) {
    return "";
  }

  if (!/^[a-z]/.test(normalized)) {
    return `u_${normalized}`.slice(0, MAX_USERNAME_LENGTH);
  }

  return normalized.slice(0, MAX_USERNAME_LENGTH);
}

export function generateUsernameFromEmail(email: string): string {
  const localPart = email.trim().toLowerCase().split("@")[0] ?? "";
  let username = sanitizeUsername(localPart);

  if (!username) {
    username = "user";
  }

  if (username.length < MIN_USERNAME_LENGTH) {
    username = username.padEnd(MIN_USERNAME_LENGTH, "0");
  }

  if (username.length > MAX_USERNAME_LENGTH) {
    username = username.slice(0, MAX_USERNAME_LENGTH);
  }

  if (!/^[a-z]/.test(username)) {
    username = `u${username}`.slice(0, MAX_USERNAME_LENGTH);
  }

  return username;
}

export function validateUsername(username: string): UsernameValidationResult {
  const normalized = username.trim().toLowerCase();

  if (normalized.length < MIN_USERNAME_LENGTH) {
    return {
      valid: false,
      error: `Username must be at least ${MIN_USERNAME_LENGTH} characters.`,
    };
  }

  if (normalized.length > MAX_USERNAME_LENGTH) {
    return {
      valid: false,
      error: `Username must be at most ${MAX_USERNAME_LENGTH} characters.`,
    };
  }

  if (!USERNAME_PATTERN.test(normalized)) {
    return {
      valid: false,
      error:
        "Username must start with a letter, contain only lowercase letters, numbers, and underscores, and not end with an underscore.",
    };
  }

  if (RESERVED_USERNAMES.has(normalized)) {
    return {
      valid: false,
      error: "This username is reserved.",
    };
  }

  return { valid: true };
}
