// // utils/userActionLogger.js
// const UserActionLog = require("../models/userActionLogModel");
// const logUserAction = async ({ userId, orgId = null, action, model = null, details = {}, req = null }) => {
//   try {
//     // Get IP address reliably
//     const ipAddress = req.headers['x-forwarded-for']?.split(',')[0].trim() || req.ip;

//     const logData = {
//       userId,
//       orgId,
//       action,
//       model,
//       details,
//       ipAddress,
//       userAgent: req?.headers["user-agent"] || null,
//     };

//     await UserActionLog.create(logData);
//   } catch (err) {
//     console.error("Failed to log user action:", err);
//   }
// };
// module.exports = { logUserAction };
// utils/userActionLogger.js


const pool = require("../config/db"); // your pg connection

const logUserAction = async ({
  userId,
  orgId = null,
  action,
  model = null,
  details = {},
  req = null,
}) => {
  try {
    if (!userId || !action) return;

    // Get IP safely
    const ipAddress =
      req?.headers["x-forwarded-for"]?.split(",")[0]?.trim() ||
      req?.ip ||
      null;

    const userAgent = req?.headers["user-agent"] || null;

    const query = `
      INSERT INTO user_action_logs 
      (user_id, org_id, action, model, details, ip_address, user_agent)
      VALUES ($1, $2, $3, $4, $5, $6, $7)
    `;

    const values = [
      userId,
      orgId || null, // optional orgId
      action,
      model,
      JSON.stringify(details || {}), //  JSONB
      ipAddress,
      userAgent,
    ];

    await pool.query(query, values);
  } catch (err) {
    console.error("Failed to log user action:", err.message);
  }
};

module.exports = { logUserAction };
