const { query } = require('../lib/db')

/**
 * Insert a device event record
 * @param {Object} event
 * @param {string} event.device_id
 * @param {number} event.user_id
 * @param {string} [event.event_type] - defaults to 'device_error'
 * @param {string|null} [event.error_code]
 * @param {number|null} [event.temperature]
 * @param {Object} event.payload - raw payload, will be JSON-stringified
 * @returns {Promise<Array>} query result
 */
async function create(event) {
  return query(
    'INSERT INTO device_events (device_id, user_id, event_type, error_code, temperature, payload_json) VALUES (:device_id, :user_id, :event_type, :error_code, :temperature, :payload_json)',
    {
      device_id: event.device_id,
      user_id: event.user_id,
      event_type: event.event_type || 'device_error',
      error_code: event.error_code || null,
      temperature: event.temperature || null,
      payload_json: JSON.stringify(event.payload || {})
    }
  )
}

module.exports = {
  create
}
