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

async function insert({ userId = null, action, detail = null, ip = null }) {
  const res = await query(
    'INSERT INTO activity_log (user_id, action, detail, ip) VALUES (?, ?, ?, ?)',
    [userId, action, detail, ip],
  )
  return res.insertId
}

async function list({ limit = 50, offset = 0 } = {}) {
  return query(
    'SELECT a.id, a.user_id, u.username, a.action, a.detail, a.ip, a.created_at ' +
      'FROM activity_log a LEFT JOIN users u ON u.id = a.user_id ' +
      'ORDER BY a.id DESC LIMIT ? OFFSET ?',
    [limit, offset],
  )
}

module.exports = { insert, list }
