import { customAlphabet } from 'nanoid'

// Human-safe alphabet: no 0/O, 1/I/l confusion
const safeAlphabet = '23456789ABCDEFGHJKLMNPQRSTUVWXYZ'
const generateCode = customAlphabet(safeAlphabet, 6)

/**
 * Generate a unique, human-safe, bank-compatible payment reference.
 * Format: PREFIX-XXXXXX-NN where:
 * - PREFIX is org configurable (default "PNPL")
 * - XXXXXX is 6-char alphanumeric (safe chars only)
 * - NN is amount pounds (helps manual matching)
 * Total max 18 chars (UK bank ref limit)
 */
export function generateReference(prefix: string = 'PNPL', amountPence?: number): string {
  const code = generateCode()
  const amountSuffix = amountPence ? Math.floor(amountPence / 100).toString().slice(-3) : ''
  const ref = amountSuffix ? `${prefix}-${code}-${amountSuffix}` : `${prefix}-${code}`

  // UK BACS reference max 18 chars
  if (ref.length > 18) {
    return `${prefix.slice(0, 4)}-${code}`
  }
  return ref
}

/**
 * Normalize a reference for matching (strip spaces, dashes, uppercase)
 */
export function normalizeReference(ref: string): string {
  return ref.replace(/[\s\-]/g, '').toUpperCase()
}

/**
 * Check if two references match (fuzzy matching for bank statements)
 */
export function referencesMatch(ref1: string, ref2: string): boolean {
  return normalizeReference(ref1) === normalizeReference(ref2)
}
