import type { FileEntry } from '@/types/api'

export type FileSortKey = 'name' | 'size' | 'modified'
export type FileSortOrder = 'asc' | 'desc'

const TYPE_ORDER: Record<FileEntry['type'], number> = {
  directory: 0,
  symlink: 1,
  file: 2,
}

export function sortFileEntries(
  items: FileEntry[],
  sortBy: FileSortKey,
  order: FileSortOrder,
): FileEntry[] {
  const dir = order === 'asc' ? 1 : -1
  return [...items].sort((a, b) => {
    const ta = TYPE_ORDER[a.type] ?? 9
    const tb = TYPE_ORDER[b.type] ?? 9
    if (ta !== tb) return ta - tb

    let cmp = 0
    if (sortBy === 'name') {
      cmp = a.name.localeCompare(b.name)
    } else if (sortBy === 'size') {
      cmp = (a.size ?? 0) - (b.size ?? 0)
    } else {
      cmp = (a.modified ?? '').localeCompare(b.modified ?? '')
    }
    return cmp * dir
  })
}

export const FILE_EXT_FILTERS: { title: string; value: string }[] = [
  { title: '全部', value: '' },
  { title: '.conf / .ini', value: 'conf,ini' },
  { title: '.log', value: 'log' },
  { title: '.sh', value: 'sh' },
  { title: '.py', value: 'py' },
  { title: '.json', value: 'json' },
  { title: '.yml / .yaml', value: 'yml,yaml' },
  { title: '.txt', value: 'txt' },
  { title: '.php', value: 'php' },
  { title: '.js / .ts', value: 'js,ts' },
]

export function matchesExtensionFilter(name: string, filter: string): boolean {
  if (!filter) return true
  const lower = name.toLowerCase()
  return filter.split(',').some((ext) => lower.endsWith(`.${ext.trim()}`))
}

export function isArchiveFile(name: string): boolean {
  const lower = name.toLowerCase()
  return lower.endsWith('.tar.gz') || lower.endsWith('.tgz') || lower.endsWith('.zip')
}
