/**
 * Discord Action Log — Trinity Console view
 * REQ-2026-04-15-discord-action-log (Chronicler #92, Issue #1)
 *
 * GET /admin/discord-log — recent 100 actions, filterable by action_type and discord_id search.
 */

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

const ACTION_TYPES = [
  'reaction_role_add',
  'reaction_role_remove',
  'wanderer_assigned',
  'welcome_dm',
  'link_reminder_dm'
];

router.get('/', async (req, res) => {
  try {
    const { action_type, search } = req.query;
    const params = [];
    let where = 'WHERE 1=1';
    let p = 0;

    if (action_type && ACTION_TYPES.includes(action_type)) {
      p++;
      where += ` AND action_type = $${p}`;
      params.push(action_type);
    }
    if (search && search.trim()) {
      p++;
      where += ` AND (discord_id = $${p} OR username ILIKE $${p + 1})`;
      params.push(search.trim());
      p++;
      params.push(`%${search.trim()}%`);
    }

    const result = await db.query(
      `SELECT * FROM discord_action_log ${where}
       ORDER BY created_at DESC LIMIT 100`,
      params
    );

    res.render('admin/discord-log', {
      title: 'Discord Action Log',
      currentPath: '/discord-log',
      logs: result.rows,
      actionTypes: ACTION_TYPES,
      filters: { action_type, search },
      adminUser: req.user,
      layout: 'layout'
    });
  } catch (err) {
    console.error('[DiscordLog] Route error:', err);
    res.status(500).send('Error loading action log');
  }
});

module.exports = router;
