const express = require('express');
const router = express.Router();
const db = require('../../database');

router.get('/', (req, res) => {
    res.render('admin/audit/index', { title: 'Admin Audit Log' });
});

router.get('/feed', async (req, res) => {
    const page = parseInt(req.query.page) || 1;
    const limit = 20;
    const offset = (page - 1) * limit;
    const filterType = req.query.type || '';

    let query = `
        SELECT id, admin_discord_id, admin_username, action_type, target_identifier, details, performed_at 
        FROM admin_audit_log
    `;
    const params = [];

    if (filterType) {
        query += ` WHERE action_type = $1 `;
        params.push(filterType);
    }

    query += ` ORDER BY performed_at DESC LIMIT $${params.length + 1} OFFSET $${params.length + 2}`;
    params.push(limit, offset);

    try {
        const { rows: logs } = await db.query(query, params);
        res.render('admin/audit/_feed', { logs, page, filterType, layout: false });
    } catch (error) {
        console.error("Audit Log Error:", error);
        res.status(500).send("<div class='text-red-500 p-4'>Error loading audit logs.</div>");
    }
});

module.exports = router;
