const { query } = require('../config/database');
const logger = require('../utils/logger');

async function logAudit({ userId, action, entity, entityId, oldData, newData, req }) {
  try {
    await query(
      `INSERT INTO audit_logs (user_id, action, entity, entity_id, old_data, new_data, ip_address, user_agent)
       VALUES ($1,$2,$3,$4,$5,$6,$7,$8)`,
      [
        userId || null,
        action,
        entity || null,
        entityId || null,
        oldData ? JSON.stringify(oldData) : null,
        newData ? JSON.stringify(newData) : null,
        req?.ip || null,
        req?.headers?.['user-agent'] || null,
      ]
    );
  } catch (err) {
    logger.error('Audit log failed:', err.message);
  }
}

module.exports = { logAudit };
