const activityDb = require('./activity.db')

const logger = require('../../utils/logger')('activity')

/**
 * Record an admin action. `detail` may be an object (stored as JSON). Never throws
 * into the request path — logging must not break the action it records.
 */
async function log({ req, userId, action, detail }) {
  try {
    const resolvedUserId = userId ?? (req && req.user ? req.user.id : null)
    const ip = req ? req.ip : null
    let detailStr = null
    if (detail != null) detailStr = typeof detail === 'string' ? detail : JSON.stringify(detail)
    await activityDb.insert({ userId: resolvedUserId, action, detail: detailStr, ip })
  } catch (err) {
    logger.error(`failed to record action "${action}"`, { error: err.message })
  }
}

async function list(opts) {
  return activityDb.list(opts)
}

module.exports = { log, list }
