'use strict';

const { pool } = require('./db');
const { requestIp } = require('./utils');

async function writeAudit({ req, actorType, actorId = null, actorName = null, actionKey, entityType = null, entityId = null, details = null, connection = null }) {
  const db = connection || pool;
  try {
    await db.execute(
      `INSERT INTO audit_logs
       (actor_type, actor_id, actor_name, action_key, entity_type, entity_id, details_json, ip_address)
       VALUES (?, ?, ?, ?, ?, ?, ?, ?)`,
      [
        actorType,
        actorId,
        actorName,
        actionKey,
        entityType,
        entityId === null ? null : String(entityId),
        details ? JSON.stringify(details) : null,
        req ? requestIp(req) : null,
      ],
    );
  } catch (error) {
    // Audit failure must not destroy the business transaction or login.
    console.error('Audit log failed:', error.message);
  }
}

module.exports = { writeAudit };
