const db = require('../config/db');

// ── GET /api/audit-logs ──
// Query params: user_id, action, entity_type, entity_id, from_date, to_date, page, limit
exports.getAll = async (req, res, next) => {
  try {
    const {
      user_id, action, entity_type, entity_id,
      from_date, to_date,
      page = 1, limit = 50,
    } = req.query;

    const conditions = [];
    const params = [];

    if (user_id) {
      conditions.push('al.user_id = ?');
      params.push(parseInt(user_id, 10));
    }
    if (action) {
      conditions.push('al.action = ?');
      params.push(action);
    }
    if (entity_type) {
      conditions.push('al.entity_type = ?');
      params.push(entity_type);
    }
    if (entity_id) {
      conditions.push('al.entity_id = ?');
      params.push(parseInt(entity_id, 10));
    }
    if (from_date) {
      conditions.push('al.created_at >= ?');
      params.push(from_date);
    }
    if (to_date) {
      conditions.push('al.created_at <= ?');
      params.push(to_date + ' 23:59:59');
    }

    const where = conditions.length > 0 ? 'WHERE ' + conditions.join(' AND ') : '';
    const offset = (parseInt(page, 10) - 1) * parseInt(limit, 10);

    // Count total
    const [countRows] = await db.query(
      `SELECT COUNT(*) AS total FROM audit_logs al ${where}`,
      params
    );
    const total = countRows[0].total;

    // Fetch page
    const [rows] = await db.query(
      `SELECT al.*, u.username, u.full_name
       FROM audit_logs al
       JOIN users u ON u.id = al.user_id
       ${where}
       ORDER BY al.created_at DESC
       LIMIT ? OFFSET ?`,
      [...params, parseInt(limit, 10), offset]
    );

    // Parse JSON details
    const logs = rows.map(r => ({
      ...r,
      details: typeof r.details === 'string' ? JSON.parse(r.details) : r.details,
    }));

    res.json({
      data: logs,
      pagination: {
        page: parseInt(page, 10),
        limit: parseInt(limit, 10),
        total,
        pages: Math.ceil(total / parseInt(limit, 10)),
      },
    });
  } catch (err) {
    next(err);
  }
};

// ── GET /api/audit-logs/summary ──
// Returns action counts grouped by entity_type and action for a date range
exports.getSummary = async (req, res, next) => {
  try {
    const { from_date, to_date } = req.query;
    const conditions = [];
    const params = [];

    if (from_date) {
      conditions.push('created_at >= ?');
      params.push(from_date);
    }
    if (to_date) {
      conditions.push('created_at <= ?');
      params.push(to_date + ' 23:59:59');
    }

    const where = conditions.length > 0 ? 'WHERE ' + conditions.join(' AND ') : '';

    const [rows] = await db.query(
      `SELECT entity_type, action, COUNT(*) AS count
       FROM audit_logs
       ${where}
       GROUP BY entity_type, action
       ORDER BY count DESC`,
      params
    );

    // Also get per-user activity counts
    const [userActivity] = await db.query(
      `SELECT al.user_id, u.full_name, u.username, COUNT(*) AS action_count
       FROM audit_logs al
       JOIN users u ON u.id = al.user_id
       ${where}
       GROUP BY al.user_id, u.full_name, u.username
       ORDER BY action_count DESC`,
      params
    );

    res.json({
      breakdown: rows,
      user_activity: userActivity,
    });
  } catch (err) {
    next(err);
  }
};

// ── GET /api/audit-logs/entity/:type/:id ──
// Get audit history for a specific entity
exports.getEntityHistory = async (req, res, next) => {
  try {
    const { type, id } = req.params;

    const [rows] = await db.query(
      `SELECT al.*, u.username, u.full_name
       FROM audit_logs al
       JOIN users u ON u.id = al.user_id
       WHERE al.entity_type = ? AND al.entity_id = ?
       ORDER BY al.created_at DESC
       LIMIT 100`,
      [type, parseInt(id, 10)]
    );

    const logs = rows.map(r => ({
      ...r,
      details: typeof r.details === 'string' ? JSON.parse(r.details) : r.details,
    }));

    res.json(logs);
  } catch (err) {
    next(err);
  }
};
