import { getDb } from "../config/db.js";

export const listAuditLogs = async (req, res) => {
  const db = getDb();
  const { role, notary_id } = req.user;
  
  let query = `
    SELECT al.id, al.user_id, u.name as user_name, al.action, al.description, al.ip_address, al.created_at
    FROM audit_logs al
    JOIN users u ON u.id = al.user_id
  `;
  const params = [];

  if (role === 'owner') {
    query += " WHERE u.notary_id = ?";
    params.push(notary_id);
  } else if (!['super_admin', 'ministry_justice', 'ministry_finance'].includes(role)) {
    // Non-privileged roles can only see their own logs
    query += " WHERE al.user_id = ?";
    params.push(req.user.id);
  }

  query += " ORDER BY al.created_at DESC LIMIT 100";

  const [rows] = await db.execute(query, params);
  res.json(rows);
};
