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 containers: any[] = []
  try {
    containers = await query(`
      SELECT DISTINCT container_name
      FROM server_containers
      WHERE target_id = $1
        AND collected_at = (
          SELECT MAX(collected_at) 
          FROM server_containers 
          WHERE target_id = $1
        )
      ORDER BY container_name ASC
    `, [targetId])
  } catch (e) {
    containers = []
  }
  
  return containers.map((c: any) => c.container_name)
})
