/**
 * Asset URL Resolution Utility
 *
 * Resolves relative asset paths to absolute backend URLs for playback and preloading.
 */

import { baseURLApi } from '../config';

/**
 * Resolves an asset path to its full playback URL.
 *
 * Handles:
 * - data: and blob: URLs (passthrough)
 * - /api/file/download URLs (passthrough)
 * - /file/download URLs (prepend baseURLApi)
 * - Full http/https URLs (passthrough)
 * - Relative paths (convert to /api/file/download?privateUrl=...)
 *
 * @param value - The asset URL or path to resolve
 * @returns The resolved full URL, or empty string if no value
 */
export const resolveAssetPlaybackUrl = (value?: string): string => {
  const normalized = String(value || '').trim();
  if (!normalized) return '';

  // Data and blob URLs pass through
  if (normalized.startsWith('data:') || normalized.startsWith('blob:'))
    return normalized;

  // Already an API file download URL
  if (normalized.startsWith('/api/file/download')) return normalized;

  // File download path (prepend API base)
  if (normalized.startsWith('/file/download'))
    return `${baseURLApi}${normalized}`;

  // Full URLs pass through
  if (normalized.startsWith('http://') || normalized.startsWith('https://'))
    return normalized;

  // Relative path - convert to API download URL
  const normalizedPrivateUrl = normalized.replace(/^\/+/, '');
  return `${baseURLApi}/file/download?privateUrl=${encodeURIComponent(normalizedPrivateUrl)}`;
};
