import { createId } from "@paralleldrive/cuid2"

// 允许的 MIME 类型：图片、PDF、Office 文档、文本、压缩包
export const ALLOWED_MIME_TYPES = [
  "image/jpeg",
  "image/png",
  "image/gif",
  "image/webp",
  "image/svg+xml",
  "application/pdf",
  "application/msword",
  "application/vnd.openxmlformats-officedocument.wordprocessingml.document",
  "application/vnd.ms-excel",
  "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",
  "application/vnd.ms-powerpoint",
  "application/vnd.openxmlformats-officedocument.presentationml.presentation",
  "text/plain",
  "text/markdown",
  "application/zip",
  "application/x-rar-compressed",
] as const

// 最大文件大小：10MB
export const MAX_FILE_SIZE = 10 * 1024 * 1024

/**
 * 判断 MIME 类型是否在允许列表中
 */
export function isAllowedMimeType(mimeType: string): boolean {
  return (ALLOWED_MIME_TYPES as readonly string[]).includes(mimeType)
}

/**
 * 从文件名中提取扩展名（小写，不含点）
 */
export function getFileExtension(filename: string): string {
  const idx = filename.lastIndexOf(".")
  if (idx <= 0 || idx === filename.length - 1) return ""
  return filename.slice(idx + 1).toLowerCase()
}

/**
 * 根据原始文件名生成存储路径：uploads/YYYY-MM/cuid.ext
 * 路径相对于 public/ 目录
 */
export function generateStoragePath(originalName: string): string {
  const ext = getFileExtension(originalName)
  const now = new Date()
  const year = now.getFullYear()
  const month = String(now.getMonth() + 1).padStart(2, "0")
  const monthDir = `${year}-${month}`
  const id = createId()
  const filename = ext ? `${id}.${ext}` : id
  return `uploads/${monthDir}/${filename}`
}

/**
 * 将字节数格式化为人类可读的字符串
 */
export function formatFileSize(bytes: number): string {
  if (bytes <= 0) return "0 B"
  const units = ["B", "KB", "MB", "GB", "TB"]
  const i = Math.min(
    units.length - 1,
    Math.floor(Math.log(bytes) / Math.log(1024))
  )
  const value = bytes / Math.pow(1024, i)
  const rounded = i === 0 ? value.toString() : value.toFixed(1)
  return `${rounded} ${units[i]}`
}
