const MAX_SLUG_LENGTH = 48;

export function slugify(text: string): string {
  return text
    .toLowerCase()
    .replace(/[^a-z0-9]+/g, "-")
    .replace(/^-+|-+$/g, "")
    .slice(0, MAX_SLUG_LENGTH)
    .replace(/-+$/, "");
}

/**
 * Deterministic branch-name prefix for an issue. Every fix branch for an issue
 * starts with this, regardless of the summary used to build the slug. The
 * trailing `-` disambiguates keys that share a prefix (e.g. `SUB-1` vs `SUB-10`).
 */
export function buildBranchPrefix(issueKey: string): string {
  return `fix/${issueKey}-`;
}

export function buildBranchName(issueKey: string, summary: string): string {
  const slug = slugify(summary);
  return `${buildBranchPrefix(issueKey)}${slug}`;
}
