const invalidSegmentCharacters = /[<>:"/\\|?*\u0000-\u001f]/g;
const trailingDotsOrSpaces = /[.\s]+$/g;
const reservedWindowsName = /^(con|prn|aux|nul|com[1-9]|lpt[1-9])(?:\..*)?$/i;
const caseNumberPattern = /^ORP-\d{6,}$/;

export type OrphanUploadIdentity = {
  orphanId: string;
  orphanName: string;
  caseNumber: string;
};

function safeSegment(value: string): string {
  const segment = value
    .normalize("NFC")
    .replace(invalidSegmentCharacters, "-")
    .replace(/\s+/g, " ")
    .trim()
    .replace(trailingDotsOrSpaces, "");

  if (!segment) throw new Error("Invalid orphan upload folder name");
  return reservedWindowsName.test(segment) ? `_${segment}` : segment;
}

export function orphanUploadFolderName(identity: OrphanUploadIdentity): string {
  if (!caseNumberPattern.test(identity.caseNumber)) {
    throw new Error("Invalid orphan case number");
  }

  const suffix = ` - ${identity.caseNumber}`;
  const maxNameLength = Math.max(1, 180 - suffix.length);
  return `${safeSegment(identity.orphanName).slice(0, maxNameLength)}${suffix}`;
}
