const { AuditLog, User } = require('../models');
const { Op } = require('sequelize');

class AuditLogController {
  async getAll(req, res, next) {
    try {
      const { action, table_name, user_id, limit, offset } = req.query;
      const where = {};
      if (action) where.action = action;
      if (table_name) where.table_name = table_name;
      if (user_id) where.user_id = user_id;

      const logs = await AuditLog.findAndCountAll({
        where,
        include: [{ model: User, attributes: ['id', 'username', 'full_name'] }],
        order: [['created_at', 'DESC']],
        limit: parseInt(limit) || 50,
        offset: parseInt(offset) || 0,
      });

      res.json({
        logs: logs.rows,
        total: logs.count,
        page: Math.floor((parseInt(offset) || 0) / (parseInt(limit) || 50)) + 1,
      });
    } catch (error) {
      next(error);
    }
  }

  async getById(req, res, next) {
    try {
      const log = await AuditLog.findByPk(req.params.id, {
        include: [{ model: User, attributes: ['id', 'username', 'full_name'] }],
      });
      if (!log) {
        return res.status(404).json({ error: 'Audit log not found' });
      }
      res.json({ log });
    } catch (error) {
      next(error);
    }
  }

  async getActions(req, res, next) {
    try {
      const actions = await AuditLog.aggregate('action', 'DISTINCT', { plain: false });
      res.json({ actions: actions.map((a) => a.DISTINCT) });
    } catch (error) {
      next(error);
    }
  }
}

module.exports = new AuditLogController();
