const CLOUDINARY_HOST = 'res.cloudinary.com';
const FLDCDN_HOST = 'prod.fldcdn.com';

/**
 * Transforms CDN URLs to use the local proxy to avoid 418/CORS errors.
 * The proxy adds the necessary headers to bypass hotlink protection.
 */
export function getProxiedImageUrl(url: string | undefined | null): string | undefined {
  if (!url) return undefined;

  try {
    const parsed = new URL(url);

    if (parsed.host === CLOUDINARY_HOST) {
      // Transform: https://res.cloudinary.com/threender/...
      // To: /api/images/threender/...
      return `/api/images${parsed.pathname}${parsed.search}`;
    }

    if (parsed.host === FLDCDN_HOST) {
      // Transform: https://prod.fldcdn.com/...
      // To: /api/fldcdn/...
      return `/api/fldcdn${parsed.pathname}${parsed.search}`;
    }
  } catch {
    // If URL parsing fails, return original
  }

  return url;
}

/**
 * Get the best available image URL from pictureUrls object
 */
export function getBestImageUrl(
  pictureUrls: { small?: string; medium?: string; large?: string } | undefined,
  preferredSize: 'small' | 'medium' | 'large' = 'medium'
): string | undefined {
  if (!pictureUrls) return undefined;

  const sizes: ('small' | 'medium' | 'large')[] =
    preferredSize === 'large' ? ['large', 'medium', 'small'] :
    preferredSize === 'medium' ? ['medium', 'large', 'small'] :
    ['small', 'medium', 'large'];

  for (const size of sizes) {
    const url = pictureUrls[size];
    if (url) return getProxiedImageUrl(url);
  }

  return undefined;
}
