import { queryOne } from '../../../utils/db'
import { refreshServerTimer } from '../../../utils/server-scheduler'

export default defineEventHandler(async (event) => {
  const body = await readBody(event)
  const { server_name, server_ip, glances_url, is_active = 1, collect_interval = 60, physical_location = '운영서버실' } = body
  
  if (!server_name || !server_ip || !glances_url) {
    throw createError({
      statusCode: 400,
      message: 'server_name, server_ip, glances_url are required'
    })
  }
  
  const result = await queryOne<{ target_id: number }>(`
    INSERT INTO server_targets (server_name, server_ip, glances_url, is_active, collect_interval, physical_location)
    VALUES ($1, $2, $3, $4, $5, $6)
    RETURNING target_id
  `, [server_name, server_ip, glances_url, is_active ? 1 : 0, collect_interval, physical_location])
  
  const targetId = result?.target_id
  
  // 스케줄러에 반영
  if (is_active && targetId) {
    await refreshServerTimer(targetId)
  }
  
  return {
    success: true,
    target_id: targetId
  }
})
