import db from "../models/index.js";

const { AuditLog } = db;

/**
 * Log a sensitive action to the AuditLogs table.
 */
export const logAudit = async ({ userId, userType, action, details, req }) => {
    try {
        const ipAddress = req?.ip || req?.headers['x-forwarded-for'] || "unknown";
        
        await AuditLog.create({
            userId,
            userType,
            action,
            details: details ? JSON.stringify(details) : null,
            ipAddress
        });
        
        console.log(`[AUDIT] ${userType.toUpperCase()} (${userId}) performed ${action}`);
    } catch (error) {
        console.error("❌ Failed to create audit log:", error.message);
        // We don't throw error here to avoid blocking the main transaction if logging fails
    }
};
