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

/**
 * Logs an action to the audit_logs table.
 * @param {number} userId - The ID of the user performing the action.
 * @param {string} action - A short string identifying the action category (e.g., "LOGIN", "RENEW_LICENSE").
 * @param {string} description - Detailed description of what happened.
 * @param {string} ipAddress - The IP address of the requester (optional).
 */
export const logAction = async (userId, action, description, ipAddress = "127.0.0.1") => {
  try {
    const db = getDb();
    if (!userId) return; // Cannot log if there's no authenticated user context in some rare cases

    await db.execute(
      "INSERT INTO audit_logs (user_id, action, description, ip_address) VALUES (?, ?, ?, ?)",
      [userId, action, description, ipAddress]
    );
  } catch (error) {
    console.error("Failed to write to audit log:", error);
  }
};
