export function extensionFromMime(mime: string, filename = ''): string {
  const normalized = mime.toLowerCase();
  if (normalized === 'image/jpeg') return 'jpg';
  if (normalized === 'image/png') return 'png';
  if (normalized === 'image/webp') return 'webp';
  if (normalized === 'image/gif') return 'gif';
  if (normalized === 'video/mp4') return 'mp4';
  if (normalized === 'video/webm') return 'webm';
  const ext = filename.split('.').pop()?.toLowerCase().replace(/[^a-z0-9]/g, '');
  return ext || 'bin';
}

export function isImageMime(mime: string): boolean {
  return ['image/jpeg', 'image/png', 'image/webp', 'image/gif'].includes(mime.toLowerCase());
}

export function isVideoMime(mime: string): boolean {
  return ['video/mp4', 'video/webm', 'video/quicktime'].includes(mime.toLowerCase());
}

export function mediaUrl(cdnBaseUrl: string, key: string | null | undefined, fallback = '/assets/images/default-avatar.svg'): string {
  if (!key) return fallback;
  if (/^https?:\/\//i.test(key)) return key;
  if (cdnBaseUrl) return `${cdnBaseUrl.replace(/\/+$/, '')}/${key.replace(/^\/+/, '')}`;
  return `/r2/${key.replace(/^\/+/, '')}`;
}
