// Pure helpers — safe to import from client components.
// DB-backed helpers (generateNextStoryCode/PbiCode) live in lib/code-server.ts.

export const CODE_REGEX = /^[A-Za-z0-9._-]+$/

export const MAX_CODE_LENGTH = 30

export function isValidCode(code: string): boolean {
  return code.length > 0 && code.length <= MAX_CODE_LENGTH && CODE_REGEX.test(code)
}

export function normalizeCode(input: string | null | undefined): string | null {
  if (input == null) return null
  const trimmed = input.trim()
  return trimmed === '' ? null : trimmed
}

/**
 * Extract the trailing numeric sequence from a code (e.g. "ST-007" → 7, "T-42" → 42).
 * Non-conforming codes (no trailing digits, empty string) return Number.MAX_SAFE_INTEGER
 * so they sort to the end.
 */
export function parseCodeNumber(code: string): number {
  const m = code.match(/(\d+)$/)
  return m ? Number.parseInt(m[1], 10) : Number.MAX_SAFE_INTEGER
}
