const isAbsoluteHttpUrl = (value: string) => /^https?:\/\//i.test(value);

const runtimeEnv = ((typeof import.meta !== 'undefined' && import.meta.env) ? import.meta.env : {}) as Record<string, any>;
const configuredApiBase = (runtimeEnv.VITE_API_BASE_URL || '').trim().replace(/\/$/, '');

export function toMediaUrl(value?: string | null): string {
  const source = (value || '').trim();
  if (!source) return '';
  if (source.startsWith('data:') || source.startsWith('blob:') || source.startsWith('/')) {
    return source;
  }
  if (!isAbsoluteHttpUrl(source)) {
    return source;
  }

  if (typeof window === 'undefined') {
    return source;
  }

  const mediaEndpoint = configuredApiBase ? `${configuredApiBase}/media` : '/api/media';
  const proxied = new URL(mediaEndpoint, window.location.origin);
  proxied.searchParams.set('url', source);
  return proxied.toString();
}
