import type { Db } from '../types/db';

const { getDb } = require('../db/database.cts');

interface AuditParams {
  user_id?: number | null;
  action: string;
  entity_type?: string | null;
  entity_id?: number | null;
  details?: any;
  ip_address?: string | null;
  user_agent?: string | null;
}

/**
 * Log a security-sensitive action to the audit_log table.
 */
function logAudit({
  user_id,
  action,
  entity_type,
  entity_id,
  details,
  ip_address,
  user_agent,
}: AuditParams): void {
  const db: Db = getDb();
  try {
    db.prepare(
      `INSERT INTO audit_log (user_id, action, entity_type, entity_id, details_json, ip_address, user_agent)
       VALUES (?, ?, ?, ?, ?, ?, ?)`,
    ).run(
      user_id || null,
      action,
      entity_type || null,
      entity_id || null,
      details ? JSON.stringify(details) : null,
      ip_address || null,
      user_agent || null,
    );
  } catch (err: any) {
    // Audit logging should never crash the app
    console.error('[audit-error] Failed to log audit event:', err.message);
  }
}

module.exports = { logAudit };
