import crypto from 'crypto'

/**
 * Generate a unique license key for a LetsBe instance
 * Format: lb_inst_{32-char-hex}
 * Example: lb_inst_a1b2c3d4e5f6g7h8i9j0k1l2m3n4o5p6
 */
export function generateLicenseKey(): string {
  const randomPart = crypto.randomBytes(16).toString('hex')
  return `lb_inst_${randomPart}`
}

/**
 * Generate a Hub API key for server-to-hub communication
 * Format: hk_{40-char-hex}
 * Example: hk_a1b2c3d4e5f6g7h8i9j0k1l2m3n4o5p6q7r8s9t0
 */
export function generateHubApiKey(): string {
  const randomPart = crypto.randomBytes(20).toString('hex')
  return `hk_${randomPart}`
}

/**
 * Validate license key format
 */
export function isValidLicenseKey(key: string): boolean {
  return /^lb_inst_[a-f0-9]{32}$/.test(key)
}

/**
 * Validate hub API key format
 */
export function isValidHubApiKey(key: string): boolean {
  return /^hk_[a-f0-9]{40}$/.test(key)
}

/**
 * Slugify a company name for use as customer identifier
 * - Converts to lowercase
 * - Replaces spaces and special chars with hyphens
 * - Removes leading/trailing hyphens
 * - Limits to 32 characters
 */
export function slugifyCustomer(name: string): string {
  return name
    .toLowerCase()
    .replace(/[^a-z0-9]+/g, '-')
    .replace(/^-+|-+$/g, '')
    .substring(0, 32)
}
