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

/**
 * Write an operation log entry
 * @param {Object} options
 * @param {number|null} [options.user_id]
 * @param {number|null} [options.admin_id]
 * @param {string} options.action
 * @param {string} [options.detail]
 * @param {string} [options.ip]
 * @returns {Promise<Array>} query result
 */
async function write(options) {
  return query(
    'INSERT INTO operation_logs (user_id, admin_id, action, detail, ip) VALUES (:user_id, :admin_id, :action, :detail, :ip)',
    {
      user_id: options.user_id || null,
      admin_id: options.admin_id || null,
      action: options.action,
      detail: options.detail || '',
      ip: options.ip || ''
    }
  )
}

/**
 * Admin paginated list of operation logs with optional filters
 * @param {Object} opts
 * @param {string} [opts.type] - filter by action (LIKE match)
 * @param {string} [opts.deviceId] - filter by detail containing device ID
 * @param {number} opts.pageSize
 * @param {number} opts.offset
 * @returns {Promise<{records: Array, total: number}>}
 */
async function list({ type, deviceId, pageSize, offset }) {
  const conditions = []
  const params = {}
  if (type) {
    conditions.push('action LIKE :type')
    params.type = '%' + type + '%'
  }
  if (deviceId) {
    conditions.push('detail LIKE :device_id')
    params.device_id = '%' + deviceId + '%'
  }
  const where = conditions.length ? ' WHERE ' + conditions.join(' AND ') : ''
  const total = await query('SELECT COUNT(*) AS total FROM operation_logs' + where, params)
  const records = await query(
    'SELECT * FROM operation_logs' + where + ' ORDER BY created_at DESC' + limitClause(pageSize, offset),
    params
  )
  return { records, total: total[0].total }
}

/**
 * Count operation logs with optional filters
 * @param {Object} opts
 * @param {string} [opts.type]
 * @param {string} [opts.deviceId]
 * @returns {Promise<number>}
 */
async function count({ type, deviceId }) {
  const conditions = []
  const params = {}
  if (type) {
    conditions.push('action LIKE :type')
    params.type = '%' + type + '%'
  }
  if (deviceId) {
    conditions.push('detail LIKE :device_id')
    params.device_id = '%' + deviceId + '%'
  }
  const where = conditions.length ? ' WHERE ' + conditions.join(' AND ') : ''
  const rows = await query('SELECT COUNT(*) AS total FROM operation_logs' + where, params)
  return rows[0].total
}

module.exports = {
  write,
  list,
  count
}
