import fs from 'fs'
import path from 'path'

/**
 * Delete a file from the public directory
 */
export function deleteFile(filePath: string): boolean {
  try {
    // Convert relative path to absolute path
    const fullPath = path.join(process.cwd(), 'public', filePath)

    if (fs.existsSync(fullPath)) {
      fs.unlinkSync(fullPath)
      return true
    }
    return false
  } catch (error) {
    console.error('Error deleting file:', error)
    return false
  }
}

/**
 * Delete multiple files
 */
export function deleteFiles(filePaths: string[]): void {
  filePaths.forEach(filePath => {
    deleteFile(filePath)
  })
}

/**
 * Clean up old product files when product is updated
 */
export function cleanupOldProductFiles(oldProduct: any, newProduct: any): void {
  const filesToDelete: string[] = []

  // Check for removed images
  if (oldProduct.images && newProduct.images) {
    const removedImages = oldProduct.images.filter((img: string) =>
      !newProduct.images.includes(img)
    )
    filesToDelete.push(...removedImages)
  }

  // Check for removed video
  if (oldProduct.videoUrl && oldProduct.videoUrl !== newProduct.videoUrl) {
    filesToDelete.push(oldProduct.videoUrl)
  }

  if (filesToDelete.length > 0) {
    deleteFiles(filesToDelete)
  }
}

/**
 * Clean up all files for a product when it's deleted
 */
export function cleanupProductFiles(product: any): void {
  const filesToDelete: string[] = []

  if (product.images && product.images.length > 0) {
    filesToDelete.push(...product.images)
  }

  if (product.videoUrl) {
    filesToDelete.push(product.videoUrl)
  }

  if (filesToDelete.length > 0) {
    deleteFiles(filesToDelete)
  }
}

/**
 * Get file size in human readable format
 */
export function formatFileSize(bytes: number): string {
  if (bytes === 0) return '0 Bytes'

  const k = 1024
  const sizes = ['Bytes', 'KB', 'MB', 'GB']
  const i = Math.floor(Math.log(bytes) / Math.log(k))

  return parseFloat((bytes / Math.pow(k, i)).toFixed(2)) + ' ' + sizes[i]
}

/**
 * Validate file type for images
 */
export function isValidImageType(mimetype: string): boolean {
  return mimetype.startsWith('image/')
}

/**
 * Validate file type for videos
 */
export function isValidVideoType(mimetype: string): boolean {
  return mimetype.startsWith('video/')
}

/**
 * Generate unique filename
 */
export function generateUniqueFilename(originalName: string, mimetype: string): string {
  // Get file extension from mimetype (more reliable than filename)
  const mimeParts = mimetype.split('/')
  let extension = 'jpg' // default fallback

  if (mimeParts.length === 2) {
    const mimeType = mimeParts[1].toLowerCase()
    // Map common mimetypes to extensions
    const extensionMap: { [key: string]: string } = {
      'jpeg': 'jpg',
      'png': 'png',
      'gif': 'gif',
      'webp': 'webp',
      'mp4': 'mp4',
      'avi': 'avi',
      'mov': 'mov',
      'quicktime': 'mov'
    }
    extension = extensionMap[mimeType] || mimeType
  }

  const timestamp = Date.now()
  const random = Math.random().toString(36).substring(2, 8)
  return `${timestamp}-${random}.${extension}`
}
