// server/api/serverFile/files.get.ts
import fs from "fs"
import path from "path"
import { promisify } from "util"

const readdir = promisify(fs.readdir)
const stat = promisify(fs.stat)
const config = useRuntimeConfig()

// Lokasi folder network share (pastikan sudah di-mount / accessible dari server)
// const FOLDER_PATH = "\\\\10.10.123.49\\qris"
const FOLDER_PATH = config.public.folder_path;

export default defineEventHandler(async (event) => {
  try {
    
    // Baca semua isi folder
    const files = await readdir(FOLDER_PATH, { withFileTypes: true })

    // Filter file saja dan ambil metadata
    const list = await Promise.all(
      files
        .filter((f) => f.isFile())
        .map(async (f) => {
          const filePath = path.join(FOLDER_PATH, f.name)
          const info = await stat(filePath)
          return {
            name: f.name,
            size: info.size,
            modified: info.ctime,
            ext: path.extname(f.name),
          }
        })
    )

    return list.sort(
      (a, b) => new Date(b.modified).getTime() - new Date(a.modified).getTime()
    ) // urut terbaru
  } catch (err: any) {
    console.error("Gagal sinkronisasi file:", err.message)
    return { error: err.message }
  }
})

