// utils/mediaUtils.js
/**
 * Media utility functions for Bunny CDN integration
 */

export const mediaUtils = {
  /**
   * Validate file type and size
   */
  validateFile(file, options = {}) {
    const {
      maxSize = 50 * 1024 * 1024, // 50MB default
      allowedTypes = ['image/*', 'video/*'],
      allowVideo = true
    } = options

    const errors = []

    // Check file size
    if (file.size > maxSize) {
      errors.push(`File size exceeds ${this.formatFileSize(maxSize)} limit`)
    }

    // Check file type
    const isAllowed = allowedTypes.some(type => {
      if (type.endsWith('*')) {
        return file.type.startsWith(type.replace('*', ''))
      }
      return file.type === type
    })

    if (!isAllowed) {
      errors.push('File type not supported')
    }

    // Check video permission
    if (file.type.startsWith('video/') && !allowVideo) {
      errors.push('Video uploads not permitted')
    }

    return {
      valid: errors.length === 0,
      errors
    }
  },

  /**
   * Format file size in human readable format
   */
  formatFileSize(bytes) {
    if (!bytes || bytes === 0) return '0 B'
    if (bytes < 1024) return bytes + ' B'
    if (bytes < 1048576) return (bytes / 1024).toFixed(1) + ' KB'
    if (bytes < 1073741824) return (bytes / 1048576).toFixed(1) + ' MB'
    return (bytes / 1073741824).toFixed(1) + ' GB'
  },

  /**
   * Get file type category
   */
  getFileCategory(mimeType) {
    if (!mimeType) return 'unknown'
    if (mimeType.startsWith('image/')) return 'image'
    if (mimeType.startsWith('video/')) return 'video'
    if (mimeType.startsWith('audio/')) return 'audio'
    if (mimeType.includes('pdf')) return 'pdf'
    if (mimeType.includes('text/')) return 'text'
    return 'file'
  },

  /**
   * Generate unique filename
   */
  generateUniqueFileName(originalName) {
    const timestamp = Date.now()
    const randomId = Math.random().toString(36).substring(2, 15)
    const sanitizedName = originalName.replace(/\s+/g, '_').replace(/[^a-zA-Z0-9._-]/g, '')
    return `${timestamp}_${randomId}_${sanitizedName}`
  },

  /**
   * Extract file extension
   */
  getFileExtension(filename) {
    return filename.split('.').pop()?.toLowerCase() || ''
  },

  /**
   * Generate thumbnail URL (if Bunny supports image transformations)
   */
  getThumbnailUrl(originalUrl, options = {}) {
    const { width = 300, height = 300, quality = 80 } = options
    
    // If using Bunny Optimizer (paid feature)
    if (originalUrl.includes('.b-cdn.net')) {
      return `${originalUrl}?width=${width}&height=${height}&quality=${quality}&format=webp`
    }
    
    return originalUrl
  },

  /**
   * Check if file is an image
   */
  isImage(mimeType) {
    return mimeType?.startsWith('image/')
  },

  /**
   * Check if file is a video
   */
  isVideo(mimeType) {
    return mimeType?.startsWith('video/')
  },

  /**
   * Create image preview URL (for local files before upload)
   */
  createPreviewUrl(file) {
    return new Promise((resolve) => {
      if (!this.isImage(file.type)) {
        resolve(null)
        return
      }

      const reader = new FileReader()
      reader.onload = (e) => resolve(e.target.result)
      reader.onerror = () => resolve(null)
      reader.readAsDataURL(file)
    })
  },

  /**
   * Batch create preview URLs
   */
  async createPreviewUrls(files) {
    const promises = Array.from(files).map(async (file) => ({
      file,
      preview: await this.createPreviewUrl(file)
    }))
    
    return Promise.all(promises)
  },

  /**
   * Get folder path based on user role and franchisee
   */
  getFolderPath(user, type = 'media') {
    const baseFolder = type === 'media' ? 'media' : type
    
    if (user?.role === 'super_admin') {
      return `${baseFolder}/super_admin/`
    }
    
    return `${baseFolder}/franchisee_${user?.franchisee_id || 'unknown'}/`
  },

  /**
   * Parse Bunny CDN URL to extract file info
   */
  parseFileUrl(url) {
    try {
      const urlObj = new URL(url)
      const pathParts = urlObj.pathname.split('/').filter(Boolean)
      const fileName = pathParts[pathParts.length - 1]
      const folder = pathParts.slice(0, -1).join('/') + '/'
      
      return {
        fileName,
        folder,
        extension: this.getFileExtension(fileName),
        baseName: fileName.replace(/\.[^/.]+$/, '')
      }
    } catch (error) {
      return null
    }
  },

  /**
   * Clean up local file index (remove orphaned entries)
   */
  cleanupLocalIndex(fileIndex) {
    const now = new Date()
    const maxAge = 30 * 24 * 60 * 60 * 1000 // 30 days
    
    return fileIndex.filter(item => {
      const created = new Date(item.createdAt)
      return (now - created) < maxAge
    })
  },

  /**
   * Sort files by different criteria
   */
  sortFiles(files, criteria = 'date', order = 'desc') {
    const sorted = [...files].sort((a, b) => {
      let comparison = 0
      
      switch (criteria) {
        case 'date':
          comparison = new Date(a.createdAt) - new Date(b.createdAt)
          break
        case 'name':
          comparison = (a.originalName || a.fileName).localeCompare(b.originalName || b.fileName)
          break
        case 'size':
          comparison = (a.size || 0) - (b.size || 0)
          break
        case 'type':
          comparison = (a.type || '').localeCompare(b.type || '')
          break
        default:
          return files
      }
      
      return order === 'desc' ? -comparison : comparison
    })
    
    return sorted
  },

  /**
   * Filter files by search term
   */
  filterFiles(files, searchTerm) {
    if (!searchTerm) return files
    
    const term = searchTerm.toLowerCase()
    
    return files.filter(file => 
      (file.originalName || file.fileName || '').toLowerCase().includes(term) ||
      (file.type || '').toLowerCase().includes(term)
    )
  },

  /**
   * Group files by type
   */
  groupFilesByType(files) {
    return files.reduce((groups, file) => {
      const category = this.getFileCategory(file.type)
      
      if (!groups[category]) {
        groups[category] = []
      }
      
      groups[category].push(file)
      return groups
    }, {})
  },

  /**
   * Calculate total size of files
   */
  calculateTotalSize(files) {
    return files.reduce((total, file) => total + (file.size || 0), 0)
  },

  /**
   * Get file statistics
   */
  getFileStats(files) {
    const grouped = this.groupFilesByType(files)
    
    return {
      total: files.length,
      totalSize: this.calculateTotalSize(files),
      byType: Object.keys(grouped).reduce((stats, type) => {
        stats[type] = {
          count: grouped[type].length,
          size: this.calculateTotalSize(grouped[type])
        }
        return stats
      }, {}),
      formatted: {
        totalSize: this.formatFileSize(this.calculateTotalSize(files))
      }
    }
  }
}

export default mediaUtils
