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

export default defineEventHandler(async (event) => {
  const body = await readBody(event)
  
  if (!body || typeof body !== 'object') {
    throw createError({
      statusCode: 400,
      message: 'Invalid request body'
    })
  }
  
  const now = new Date().toLocaleString('sv-SE', { timeZone: 'Asia/Seoul' }).replace('T', ' ')
  
  let updated = 0
  
  for (const [category, metrics] of Object.entries(body)) {
    if (typeof metrics !== 'object') continue
    
    for (const [metric, values] of Object.entries(metrics as Record<string, any>)) {
      if (!values || typeof values !== 'object') continue
      
      const { warning, critical, danger } = values
      
      if (typeof warning !== 'number' || typeof critical !== 'number' || typeof danger !== 'number') {
        continue
      }
      
      if (warning < 0 || warning > 100 || critical < 0 || critical > 100 || danger < 0 || danger > 100) {
        continue
      }
      
      if (warning >= critical || critical >= danger) {
        throw createError({
          statusCode: 400,
          message: `Invalid thresholds for ${category}.${metric}: warning < critical < danger 순서여야 합니다.`
        })
      }
      
      try {
        const result = await execute(`
          UPDATE thresholds 
          SET warning = $1, critical = $2, danger = $3, updated_at = $4
          WHERE category = $5 AND metric = $6
        `, [warning, critical, danger, now, category, metric])
        if (result > 0) updated++
      } catch (e) {
        // 테이블이 없는 경우 무시
      }
    }
  }
  
  return { success: true, updated }
})
