/**
 * Query builder for safe dynamic UPDATE queries with column whitelist validation.
 * Prevents SQL injection by validating column names against allowed sets.
 */

const ALLOWED_COLUMNS = {
  devices: new Set(['name', 'device_type', 'vendor', 'lat', 'lng', 'stream_url', 'source_type', 'config']),
  users: new Set(['role', 'identifier', 'password_hash']),
  pois: new Set(['label', 'icon_type', 'lat', 'lng']),
}

export function buildUpdateQuery(table, allowedColumns, updates) {
  if (!ALLOWED_COLUMNS[table]) throw new Error(`Unknown table: ${table}`)
  const columns = allowedColumns || ALLOWED_COLUMNS[table]
  const clauses = []
  const params = []
  for (const [column, value] of Object.entries(updates)) {
    if (!columns.has(column)) throw new Error(`Invalid column: ${column} for table: ${table}`)
    clauses.push(`${column} = ?`)
    params.push(value)
  }
  if (clauses.length === 0) return { query: '', params: [] }
  return { query: `UPDATE ${table} SET ${clauses.join(', ')} WHERE id = ?`, params }
}

export function getAllowedColumns(table) {
  return ALLOWED_COLUMNS[table] || new Set()
}
