// Image utility functions for handling fallbacks and uploads

export interface ImageFallback {
  type: "track" | "album" | "artist" | "playlist" | "user"
  query?: string
}

/**
 * Get a fallback image URL based on type
 * Uses only existing images in /public folder
 */
export function getImageFallback(type: ImageFallback["type"], query?: string): string {
  const fallbacks: Record<ImageFallback["type"], string> = {
    track: "/abstract-music-album.png",
    album: "/new-music-release.jpg",
    artist: "/placeholder-user.jpg",
    playlist: "/music-playlist-concept.png",
    user: "/placeholder-user.jpg",
  }

  return fallbacks[type] || "/abstract-music-album.png"
}

/**
 * Get optimized image URL with fallback
 * Supports Vercel Blob URLs and relative paths
 */
export function getImageUrl(url: string | null | undefined, fallbackType: ImageFallback["type"]): string {
  if (!url) {
    return getImageFallback(fallbackType)
  }

  // If it's a valid URL (http, https, or blob), return as is
  if (url.startsWith("http") || url.startsWith("https") || url.startsWith("blob:")) {
    return url
  }

  // If it's a relative path starting with /, return as is
  if (url.startsWith("/")) {
    return url
  }

  // Default fallback for invalid URLs
  return getImageFallback(fallbackType)
}

/**
 * Validate image file before upload
 */
export function validateImageFile(file: File): { valid: boolean; error?: string } {
  const maxSize = 5 * 1024 * 1024 // 5MB
  const allowedTypes = ["image/jpeg", "image/jpg", "image/png", "image/webp"]

  if (!allowedTypes.includes(file.type)) {
    return {
      valid: false,
      error: "Format non supporté. Utilisez JPG, PNG ou WebP.",
    }
  }

  if (file.size > maxSize) {
    return {
      valid: false,
      error: "Fichier trop volumineux. Maximum 5MB.",
    }
  }

  return { valid: true }
}

/**
 * Generate a thumbnail preview from an image file
 */
export function generateImagePreview(file: File): Promise<string> {
  return new Promise((resolve, reject) => {
    const reader = new FileReader()
    reader.onloadend = () => {
      resolve(reader.result as string)
    }
    reader.onerror = reject
    reader.readAsDataURL(file)
  })
}

/**
 * Upload image to blob storage
 */
export async function uploadImage(file: File, folder: "covers" | "avatars" | "banners"): Promise<string> {
  const formData = new FormData()
  formData.append("file", file)
  formData.append("folder", folder)

  const response = await fetch("/api/upload/image", {
    method: "POST",
    body: formData,
  })

  if (!response.ok) {
    const error = await response.json()
    throw new Error(error.error || "Échec du téléchargement")
  }

  const data = await response.json()
  return data.url
}
