import { pool } from '../config/database';

export interface AuditLogData {
  user_id?: number | null;
  action: string;
  entity_type: string;
  entity_id?: number | null;
  old_values?: any;
  new_values?: any;
  ip_address?: string;
  user_agent?: string;
}

export const createAuditLog = async (data: AuditLogData, connection?: any): Promise<void> => {
  const db = connection || pool;
  
  const query = `
    INSERT INTO audit_logs 
    (user_id, action, entity_type, entity_id, old_values, new_values, ip_address, user_agent)
    VALUES (?, ?, ?, ?, ?, ?, ?, ?)
  `;
  
  await db.query(query, [
    data.user_id || null,
    data.action,
    data.entity_type,
    data.entity_id || null,
    data.old_values ? JSON.stringify(data.old_values) : null,
    data.new_values ? JSON.stringify(data.new_values) : null,
    data.ip_address || null,
    data.user_agent || null
  ]);
};

export const findAll = async (filters: any = {}, connection?: any): Promise<any[]> => {
  const db = connection || pool;
  let query = 'SELECT * FROM audit_logs WHERE 1=1';
  const params: any[] = [];
  
  if (filters.user_id) {
    query += ' AND user_id = ?';
    params.push(filters.user_id);
  }
  if (filters.action) {
    query += ' AND action = ?';
    params.push(filters.action);
  }
  if (filters.entity_type) {
    query += ' AND entity_type = ?';
    params.push(filters.entity_type);
  }
  
  query += ' ORDER BY created_at DESC';
  
  if (filters.limit) {
    query += ' LIMIT ? OFFSET ?';
    params.push(parseInt(filters.limit), parseInt(filters.offset || 0));
  }
  
  const [rows] = await db.query(query, params);
  return rows as any[];
};

export const findById = async (id: number, connection?: any): Promise<any | null> => {
  const db = connection || pool;
  const [rows] = await db.query('SELECT * FROM audit_logs WHERE id = ?', [id]);
  return (rows as any[])[0] || null;
};

export const getRecentActivity = async (limit: number = 10, connection?: any): Promise<any[]> => {
  const db = connection || pool;
  // Nous filtrons les actions importantes pour le tableau de bord
  const query = `
    SELECT id, user_id, action, entity_type, entity_id, created_at 
    FROM audit_logs 
    WHERE action IN ('CREATE_USER', 'CREATE', 'UPDATE_STATUS', 'ASSIGN', 'CREATE_PAYMENT', 'CONFIRM_VISIT', 'LEAD_UPDATED')
    ORDER BY created_at DESC 
    LIMIT ?
  `;
  const [rows] = await db.query(query, [limit]);
  return rows as any[];
};
