/**
 * Audit Logger - Security event logging
 */

const { getDatabase } = require('../database/connection');
const crypto = require('crypto');

/**
 * Log an audit event
 * @param {Object} event - Event data
 */
function logAuditEvent(event) {
  const db = getDatabase();
  if (!db) {
    // Silently fail if database not initialized
    console.log('[AUDIT]', event.eventType, event.userId || 'anonymous');
    return;
  }
  
  try {
    const stmt = db.prepare(`
      INSERT INTO audit_log (
        id, user_id, event_type, event_data, ip_address,
        user_agent, success, error_message, created_at
      ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)
    `);
    
    stmt.run(
      crypto.randomUUID(),
      event.userId || null,
      event.eventType,
      event.eventData ? JSON.stringify(event.eventData) : null,
      event.ipAddress || null,
      event.userAgent || null,
      event.success !== false ? 1 : 0,
      event.errorMessage || null,
      Date.now()
    );
  } catch (error) {
    console.error('Failed to log audit event:', error);
  }
}

/**
 * Get audit log for a user
 * @param {string} userId - User ID
 * @param {Object} options - Query options (limit, offset, eventType)
 * @returns {Array} Array of audit events
 */
function getUserAuditLog(userId, options = {}) {
  const db = getDatabase();
  if (!db) {
    throw new Error('Database not initialized');
  }
  
  const limit = options.limit || 100;
  const offset = options.offset || 0;
  
  let sql = 'SELECT * FROM audit_log WHERE user_id = ?';
  const params = [userId];
  
  if (options.eventType) {
    sql += ' AND event_type = ?';
    params.push(options.eventType);
  }
  
  sql += ' ORDER BY created_at DESC LIMIT ? OFFSET ?';
  params.push(limit, offset);
  
  const stmt = db.prepare(sql);
  const rows = stmt.all(...params);
  
  return rows.map(deserializeAuditEvent);
}

/**
 * Get recent audit events
 * @param {Object} options - Query options (limit, eventType)
 * @returns {Array} Array of audit events
 */
function getRecentAuditLog(options = {}) {
  const db = getDatabase();
  if (!db) {
    throw new Error('Database not initialized');
  }
  
  const limit = options.limit || 100;
  
  let sql = 'SELECT * FROM audit_log';
  const params = [];
  
  if (options.eventType) {
    sql += ' WHERE event_type = ?';
    params.push(options.eventType);
  }
  
  sql += ' ORDER BY created_at DESC LIMIT ?';
  params.push(limit);
  
  const stmt = db.prepare(sql);
  const rows = stmt.all(...params);
  
  return rows.map(deserializeAuditEvent);
}

function deserializeAuditEvent(row) {
  if (!row) {
    return null;
  }
  
  return {
    id: row.id,
    userId: row.user_id,
    eventType: row.event_type,
    eventData: row.event_data ? JSON.parse(row.event_data) : null,
    ipAddress: row.ip_address,
    userAgent: row.user_agent,
    success: Boolean(row.success),
    errorMessage: row.error_message,
    createdAt: row.created_at
  };
}

module.exports = {
  logAuditEvent,
  getUserAuditLog,
  getRecentAuditLog
};
