const express = require('express');
const router = express.Router();
const { getDB } = require('../config/database');
const { auth } = require('../middleware/auth');
const { ok } = require('../helpers/response');

router.get('/', auth(['Admin']), async (req, res, next) => {
  try {
    const db = getDB();
    const { level = '', limit = 100 } = req.query;
    let query = 'SELECT l.*, u.nama as user_nama FROM logs l LEFT JOIN users u ON l.user_id = u.id';
    const params = [];
    if (level) { query += ' WHERE l.level = ?'; params.push(level); }
    query += ` ORDER BY l.created_at DESC LIMIT ${Number(limit)}`;
    const [data] = await db.query(query, params);
    ok(res, { data });
  } catch (e) { next(e); }
});

router.delete('/', auth(['Admin']), async (req, res, next) => {
  try {
    const db = getDB();
    await db.query('DELETE FROM logs');
    ok(res, null, 'Log berhasil dihapus');
  } catch (e) { next(e); }
});

module.exports = router;
