/**
 * models/auditLog.js
 */

'use strict';

const { db } = require('../config/db');

const insert = db.prepare(`
  INSERT INTO audit_log (actor_id, actor_email, action, target, meta, ip, created_at)
  VALUES (?, ?, ?, ?, ?, ?, ?)
`);
const listAll = db.prepare(`
  SELECT * FROM audit_log ORDER BY created_at DESC LIMIT ? OFFSET ?
`);
const listForActor = db.prepare(`
  SELECT * FROM audit_log WHERE actor_id = ? ORDER BY created_at DESC LIMIT ? OFFSET ?
`);

function log(actor, action, target = null, meta = null, ip = null) {
  const actor_id = actor && typeof actor === 'object' ? actor.id : null;
  const actor_email = actor && typeof actor === 'object' ? actor.email : (typeof actor === 'string' ? actor : null);
  insert.run(
    actor_id,
    actor_email,
    action,
    target,
    meta ? JSON.stringify(meta) : null,
    ip,
    Date.now()
  );
}

function list(limit = 100, offset = 0) { return listAll.all(limit, offset); }
function forActor(actorId, limit = 100, offset = 0) { return listForActor.all(actorId, limit, offset); }

module.exports = { log, list, forActor };
