import { query } from '../../../utils/db'

export default defineEventHandler(async (event) => {
  const queryParams = getQuery(event)
  const targetId = queryParams.target_id as string
  
  if (!targetId) {
    throw createError({
      statusCode: 400,
      message: 'target_id is required'
    })
  }
  
  let disks: any[] = []
  try {
    disks = await query(`
      SELECT DISTINCT device_name, mount_point, fs_type, disk_total, disk_used, disk_percent
      FROM server_disks
      WHERE target_id = $1
        AND collected_at = (SELECT MAX(collected_at) FROM server_disks WHERE target_id = $1)
        AND device_name NOT LIKE '%loop%'
        AND mount_point NOT LIKE '%/snap%'
        AND fs_type NOT IN ('tmpfs', 'squashfs', 'overlay')
      ORDER BY mount_point ASC
    `, [targetId])
  } catch (e) {
    disks = []
  }
  
  return disks
})
