const express = require('express');
const db = require('../config/database');
const { auth, authorize } = require('../middleware/auth');

const router = express.Router();

router.get('/', auth, authorize('admin'), (req, res) => {
  const { page = 1, limit = 20, module, userId, action } = req.query;
  const offset = (page - 1) * limit;
  
  let query = `
    SELECT al.*, u.username, u.full_name 
    FROM activity_logs al 
    LEFT JOIN users u ON al.user_id = u.id 
    WHERE 1=1
  `;
  const params = [];
  
  if (module) {
    query += ' AND al.module = ?';
    params.push(module);
  }
  
  if (userId) {
    query += ' AND al.user_id = ?';
    params.push(parseInt(userId));
  }
  
  if (action) {
    query += ' AND al.action = ?';
    params.push(action);
  }
  
  query += ' ORDER BY al.created_at DESC LIMIT ? OFFSET ?';
  params.push(parseInt(limit), offset);
  
  const logs = db.prepare(query).all(...params);
  
  let countQuery = query.replace(/SELECT.*FROM/, 'SELECT COUNT(*) as total FROM').replace(/ORDER BY.*$/, '').replace(/ LIMIT \? OFFSET \?$/, '');
  const countParams = params.slice(0, -2);
  const countResult = db.prepare(countQuery).get(...countParams);
  
  res.json({
    logs,
    pagination: {
      page: parseInt(page),
      limit: parseInt(limit),
      total: countResult?.total || 0
    }
  });
});

router.get('/stats', auth, authorize('admin'), (req, res) => {
  const { days = 7 } = req.query;
  
  const stats = db.prepare(`
    SELECT 
      date(created_at) as date,
      COUNT(*) as count,
      module
    FROM activity_logs
    WHERE created_at >= date('now', ?)
    GROUP BY date, module
    ORDER BY date DESC
  `).all(`-${days} days`);
  
  res.json({ stats });
});

module.exports = router;
