/**
 * Activity Log Model
 * Handles activity logging operations
 */

const { query } = require("../config/database");

class ActivityLog {
  /**
   * Create activity log entry
   */
  static async create(logData) {
    const result = await query(
      `INSERT INTO activity_logs (
                user_id, action_type, entity_type, entity_id, 
                description, old_values, new_values, ip_address, user_agent
            ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)`,
      [
        logData.userId || null,
        logData.actionType,
        logData.entityType,
        logData.entityId || null,
        logData.description || null,
        logData.oldValues ? JSON.stringify(logData.oldValues) : null,
        logData.newValues ? JSON.stringify(logData.newValues) : null,
        logData.ipAddress || null,
        logData.userAgent || null,
      ],
    );

    return { id: result.insertId, ...logData };
  }

  /**
   * Get activity logs with pagination
   */
  static async findAll(options = {}) {
    const {
      page = 1,
      limit = 20,
      userId = "",
      entityType = "",
      actionType = "",
      startDate = "",
      endDate = "",
    } = options;

    const offset = (page - 1) * limit;
    let whereClause = "1=1";
    const params = [];

    if (userId) {
      whereClause += " AND a.user_id = ?";
      params.push(userId);
    }

    if (entityType) {
      whereClause += " AND a.entity_type = ?";
      params.push(entityType);
    }

    if (actionType) {
      whereClause += " AND a.action_type = ?";
      params.push(actionType);
    }

    if (startDate) {
      whereClause += " AND a.created_at >= ?";
      params.push(startDate);
    }

    if (endDate) {
      whereClause += " AND a.created_at <= ?";
      params.push(endDate);
    }

    // Get total count
    const countResult = await query(
      `SELECT COUNT(*) as total FROM activity_logs a WHERE ${whereClause}`,
      params,
    );

    // Get logs
    const logs = await query(
      `SELECT a.*, 
                    u.username,
                    CONCAT(e.first_name, ' ', e.last_name) as user_name
             FROM activity_logs a
             LEFT JOIN users u ON a.user_id = u.id
             LEFT JOIN employees e ON u.employee_id = e.id
             WHERE ${whereClause}
             ORDER BY a.created_at DESC
             LIMIT ? OFFSET ?`,
      [...params, limit, offset],
    );

    return {
      logs,
      pagination: {
        total: countResult[0].total,
        page,
        limit,
        totalPages: Math.ceil(countResult[0].total / limit),
      },
    };
  }

  /**
   * Get recent activities for dashboard
   */
  static async getRecent(limit = 10) {
    return query(
      `SELECT a.*, 
                    u.username,
                    CONCAT(e.first_name, ' ', e.last_name) as user_name
             FROM activity_logs a
             LEFT JOIN users u ON a.user_id = u.id
             LEFT JOIN employees e ON u.employee_id = e.id
             ORDER BY a.created_at DESC
             LIMIT ?`,
      [limit],
    );
  }
}

module.exports = ActivityLog;
