// Builds the auto-generated variant display name, e.g.
// "DOUBLE ARROW(2GF)-CURB-22 KT-24INCH-24.960GM" from the names of the
// masters selected on the Create Variant form. This is what gets stored in
// products.name and is what every existing screen (order dropdown, reports,
// order rows) already displays as the product name.
export interface VariantNameParts {
  itemName: string;
  categoryName?: string;
  purityName?: string;
  chainSizeName?: string;
  weightName?: string;
  wireSizeName?: string;
}

// Weight master values are free text (e.g. "24.96" or "8"); when numeric,
// append a "GM" suffix while preserving exactly the decimals the user
// entered (no forced/padded precision). Non-numeric values are passed
// through unchanged rather than dropped.
function formatWeight(weightName: string): string {
  const trimmed = weightName.trim();
  const parsed = Number.parseFloat(trimmed);
  if (Number.isNaN(parsed)) return trimmed;
  return `${trimmed}GM`;
}

export function buildVariantName(parts: VariantNameParts): string {
  const segments = [
    parts.itemName.trim(),
    parts.categoryName?.trim(),
    parts.purityName?.trim(),
    parts.chainSizeName?.trim(),
    parts.weightName ? formatWeight(parts.weightName) : undefined,
  ].filter((segment): segment is string => Boolean(segment));

  return segments.join('-');
}
