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

export default defineEventHandler(async (event) => {
  const queryParams = getQuery(event)
  
  const type = queryParams.type as string || 'short-term'
  const period = queryParams.period as string || '24h'
  
  // 기간 계산
  let interval = '24 hours'
  if (period.endsWith('h')) {
    const hours = parseInt(period)
    interval = `${hours} hours`
  } else if (period.endsWith('d')) {
    const days = parseInt(period)
    interval = `${days} days`
  }
  
  let logs: any[] = []
  try {
    logs = await query<any>(`
      SELECT id, target_id, server_name, detect_type, metric, level, 
             current_value, threshold_value, message, detected_at
      FROM anomaly_logs
      WHERE detect_type = $1
        AND detected_at::timestamp >= NOW() - INTERVAL '${interval}'
      ORDER BY detected_at DESC
      LIMIT 100
    `, [type])
  } catch (e) {
    logs = []
  }
  
  return {
    logs,
    type,
    period,
    timestamp: new Date().toISOString()
  }
})
