/** Downloads keep the server filename, or derive an extension from the actual response type. */
export function certificateDownloadFilename(
  disposition: string | undefined,
  contentType: string | undefined,
  fallbackName = "certificate",
): string {
  const encoded = disposition?.match(/filename\*=UTF-8''([^;]+)/i)?.[1];
  if (encoded) {
    try { return decodeURIComponent(encoded.trim()); } catch { /* Try the plain filename. */ }
  }
  const name = disposition?.match(/filename\s*=\s*(?:"([^"]+)"|([^;]+))/i);
  if (name) return (name[1] || name[2]).trim();
  const extensions: Record<string, string> = {
    "application/pdf": "pdf",
    "image/png": "png",
    "image/jpeg": "jpg",
    "image/webp": "webp",
    "text/html": "html",
  };
  const extension = extensions[contentType?.split(";")[0].trim().toLowerCase() ?? ""] || "bin";
  return `${fallbackName}.${extension}`;
}
