/** First word of the name, uppercased and stripped to alphanumerics — falls back to "VN"
 * so an empty/punctuation-only name still yields a usable base. Mirrors the warehouse
 * code generator (app/dashboard/warehouse/page.tsx). */
function vendorCodeBase(name: string): string {
  const firstWord = name.trim().split(/\s+/)[0] ?? ""
  const cleaned = firstWord.toUpperCase().replace(/[^A-Z0-9]/g, "")
  return cleaned.slice(0, 10) || "VN"
}

/** Appends a numeric suffix until the code doesn't collide with an existing one — the
 * backend enforces global uniqueness (409 on conflict) but has no generation of its own. */
export function generateVendorCode(name: string, existingCodes: string[]): string {
  const base = `VN-${vendorCodeBase(name)}`
  if (!existingCodes.includes(base)) return base
  let suffix = 2
  while (existingCodes.includes(`${base}${suffix}`)) suffix += 1
  return `${base}${suffix}`
}
