import { useSettingsStore } from '@/stores/settings'

export interface FileValidationResult {
  isValid: boolean
  error?: string
}

export interface FileValidationOptions {
  allowedTypes?: string[]
  maxSizeBytes?: number
  checkGlobalLimit?: boolean
}

// Common movie file extensions
export const MOVIE_FILE_EXTENSIONS = [
  '.mov', '.mp4', '.avi', '.mkv', '.wmv', '.flv', '.webm', '.m4v'
]

// Common image file extensions
export const IMAGE_FILE_EXTENSIONS = [
  '.jpg', '.jpeg', '.png', '.gif', '.bmp', '.tiff', '.tga', '.exr', '.hdr'
]

// All supported media file extensions
export const MEDIA_FILE_EXTENSIONS = [
  ...MOVIE_FILE_EXTENSIONS,
  ...IMAGE_FILE_EXTENSIONS
]

export function formatFileSize(bytes: number): string {
  if (bytes === 0) return '0 Bytes'
  
  const k = 1024
  const sizes = ['Bytes', 'KB', 'MB', 'GB', 'TB']
  const i = Math.floor(Math.log(bytes) / Math.log(k))
  
  return parseFloat((bytes / Math.pow(k, i)).toFixed(2)) + ' ' + sizes[i]
}

export function isMovieFile(fileName: string): boolean {
  const extension = '.' + fileName.split('.').pop()?.toLowerCase()
  return MOVIE_FILE_EXTENSIONS.includes(extension)
}

export function isImageFile(fileName: string): boolean {
  const extension = '.' + fileName.split('.').pop()?.toLowerCase()
  return IMAGE_FILE_EXTENSIONS.includes(extension)
}

export function isMediaFile(fileName: string): boolean {
  const extension = '.' + fileName.split('.').pop()?.toLowerCase()
  return MEDIA_FILE_EXTENSIONS.includes(extension)
}

export async function validateFile(
  file: File, 
  options: FileValidationOptions = {}
): Promise<FileValidationResult> {
  const {
    allowedTypes = MEDIA_FILE_EXTENSIONS,
    maxSizeBytes,
    checkGlobalLimit = true
  } = options

  // Check file type
  const fileExtension = '.' + file.name.split('.').pop()?.toLowerCase()
  if (!allowedTypes.includes(fileExtension)) {
    return {
      isValid: false,
      error: `File type ${fileExtension} is not allowed. Supported types: ${allowedTypes.join(', ')}`
    }
  }

  // Check global upload limit for movie files
  if (checkGlobalLimit && isMovieFile(file.name)) {
    const settingsStore = useSettingsStore()
    
    // Ensure upload limit is loaded
    if (!settingsStore.uploadLimit) {
      await settingsStore.fetchUploadLimit()
    }

    const globalLimitBytes = settingsStore.uploadLimitBytes
    if (file.size > globalLimitBytes) {
      return {
        isValid: false,
        error: `Movie file size (${formatFileSize(file.size)}) exceeds the global upload limit of ${formatFileSize(globalLimitBytes)}`
      }
    }
  }

  // Check custom size limit
  if (maxSizeBytes && file.size > maxSizeBytes) {
    return {
      isValid: false,
      error: `File size (${formatFileSize(file.size)}) exceeds the maximum allowed size of ${formatFileSize(maxSizeBytes)}`
    }
  }

  return { isValid: true }
}

export function getFileValidationErrorMessage(file: File, error: string): string {
  return `File "${file.name}": ${error}`
}

// Utility to validate multiple files
export async function validateFiles(
  files: File[], 
  options: FileValidationOptions = {}
): Promise<{ validFiles: File[]; errors: string[] }> {
  const validFiles: File[] = []
  const errors: string[] = []

  for (const file of files) {
    const result = await validateFile(file, options)
    if (result.isValid) {
      validFiles.push(file)
    } else {
      errors.push(getFileValidationErrorMessage(file, result.error!))
    }
  }

  return { validFiles, errors }
}