const CLOUDINARY_UPLOAD_SEGMENT = "/image/upload/";

function isCloudinaryUrl(url: string): boolean {
  return url.includes("res.cloudinary.com") && url.includes(CLOUDINARY_UPLOAD_SEGMENT);
}

/**
 * Returns a resized, format- and quality-optimized variant of a Cloudinary avatar URL.
 * Doubles the requested pixel size for retina displays.
 * Non-Cloudinary URLs are returned unchanged.
 */
export function cloudinaryAvatarUrl(url: string, displaySizePx: number): string {
  if (!isCloudinaryUrl(url) || url.includes(",c_fill,")) return url;

  const retinaSizePx = displaySizePx * 2;
  const transform = `w_${retinaSizePx},h_${retinaSizePx},c_fill,g_face,f_auto,q_auto`;

  return url.replace(CLOUDINARY_UPLOAD_SEGMENT, `${CLOUDINARY_UPLOAD_SEGMENT}${transform}/`);
}
