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

/** Raw row from POST /api/sync/browse (legacy `entries` field). */
export interface BrowseRawEntry {
  name: string
  is_dir?: boolean
  is_link?: boolean
  size?: string | number
  perms?: string
  permissions?: string
  owner?: string
  group?: string
  mode_octal?: string
  modified?: string
  type?: FileEntry['type']
}

export function mapBrowseEntries(raw: BrowseRawEntry[]): FileEntry[] {
  return raw
    .filter((e) => e.name && e.name !== '.' && e.name !== '..')
    .map((e) => {
      const isDir = e.type === 'directory' || Boolean(e.is_dir)
      const isLink = e.type === 'symlink' || Boolean(e.is_link)
      let size = 0
      if (!isDir && !isLink && e.size != null) {
        const n = typeof e.size === 'number' ? e.size : parseInt(String(e.size), 10)
        size = Number.isFinite(n) ? n : 0
      }
      let type: FileEntry['type'] = 'file'
      if (isDir) type = 'directory'
      else if (isLink) type = 'symlink'
      return {
        name: e.name,
        type,
        size,
        modified: e.modified ?? '',
        permissions: e.permissions ?? e.perms ?? '',
        owner: e.owner ?? '',
        group: e.group ?? '',
        mode_octal: e.mode_octal ?? '',
        link_target: (e as BrowseRawEntry & { link_target?: string }).link_target ?? null,
      }
    })
}

/** Normalize browse API body: prefers `items`, falls back to legacy `entries`. */
export function parseBrowseResponse(
  res: BrowseResponse | FileEntry[] | (BrowseResponse & { entries?: BrowseRawEntry[] }),
): { items: FileEntry[]; error?: string } {
  if (Array.isArray(res)) {
    return { items: res }
  }
  const body = res as BrowseResponse & { entries?: BrowseRawEntry[]; error?: string }
  if (Array.isArray(body.items)) {
    return { items: body.items, error: body.error }
  }
  if (body.entries?.length) {
    return { items: mapBrowseEntries(body.entries), error: body.error }
  }
  return { items: body.items ?? [], error: body.error }
}
