/**
 * User directory naming for invited team members.
 *
 * The directory lives at <projectRoot>/users/{dirName}/ and the name is
 * shown in `ls` output, error messages, and any path-based audit. We pick
 * a format that is:
 *   - readable ("who + when" is obvious from the name)
 *   - privacy-preserving (no full PII, no token)
 *   - collision-safe (3 random chars disambiguate same-day same-tail)
 *
 * Format: `user-{phoneTail4}-{yyyymmdd}-{3char}`
 * Example: `user-8000-20260621-k7f`
 */

import crypto from 'crypto'

/**
 * Generate a human-readable directory name for a new invited user.
 *
 * @param phone - The verified phone number, used only for the last 4
 *                digits. Pass '' if no phone is available — falls back to '0000'.
 * @param date  - The invite date. Defaults to now; pass a fixed date in tests.
 */
export function makeUserDirName(phone: string, date: Date = new Date()): string {
  const phoneTail = lastDigits(phone, 4).padStart(4, '0')
  const dateStr = date.toISOString().slice(0, 10).replace(/-/g, '')
  const suffix = crypto.randomBytes(3).toString('base64url')
  return `user-${phoneTail}-${dateStr}-${suffix}`
}

/** Returns true if `dirName` looks like a valid generated user dir name. */
export function isUserDirName(dirName: string): boolean {
  return /^user-[a-z0-9-]+$/i.test(dirName)
}

function lastDigits(input: string, n: number): string {
  const digits = (input || '').replace(/\D/g, '')
  return digits.slice(-n)
}
