/** URL für Übungs-Mediendateien: API mit Token (Legacy /media/ ohne Auth ist abgeschaltet). */

const API_BASE = (import.meta.env.VITE_API_URL || '').replace(/\/$/, '')

/**
 * @param {number|string} exerciseId
 * @param {object} media — exercise_media Zeile mit id, file_path
 * @returns {string|null}
 */
export function resolveExerciseMediaFileUrl(exerciseId, media) {
  if (!media?.file_path) return null
  const fp = String(media.file_path)
  if (fp.startsWith('http://') || fp.startsWith('https://')) return fp
  const token = typeof localStorage !== 'undefined' ? localStorage.getItem('authToken') : ''
  const q = token ? `?ssetoken=${encodeURIComponent(token)}` : ''
  const id = media.id
  if (id == null || exerciseId == null) return null
  return `${API_BASE}/api/exercises/${exerciseId}/media/${id}/file${q}`
}

/**
 * Direkt-URL für Archiv-Asset (Picker/Vorschau ohne exercise_media-Zeile).
 * @param {number|string} assetId — media_assets.id
 * @returns {string|null}
 */
export function resolveMediaAssetFileUrl(assetId) {
  if (assetId == null) return null
  const token = typeof localStorage !== 'undefined' ? localStorage.getItem('authToken') : ''
  const q = token ? `?ssetoken=${encodeURIComponent(token)}` : ''
  return `${API_BASE}/api/media-assets/${assetId}/file${q}`
}
