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

/**
 * MCP Logs Module — Trinity Console
 * 
 * View and filter command execution logs from Trinity Core.
 * 
 * GET /admin/mcp-logs — Main logs page with filters
 * 
 * Chronicler #78 | April 11, 2026
 */

const SERVERS = [
  'command-center', 'tx1-dallas', 'nc1-charlotte',
  'panel-vps', 'dev-panel', 'wiki-vps', 'services-vps', 'trinity-core'
];

router.get('/', async (req, res) => {
  try {
    const { server, success, limit = 50, offset = 0 } = req.query;

    // Build filtered query
    let where = 'WHERE 1=1';
    const params = [];
    let p = 0;

    if (server) {
      p++;
      where += ` AND server = $${p}`;
      params.push(server);
    }

    if (success !== undefined && success !== '') {
      p++;
      where += ` AND success = $${p}`;
      params.push(success === 'true');
    }

    // Get logs
    const logsResult = await db.query(
      `SELECT * FROM mcp_logs ${where} ORDER BY executed_at DESC LIMIT $${p + 1} OFFSET $${p + 2}`,
      [...params, parseInt(limit), parseInt(offset)]
    );

    // Get total count
    const countResult = await db.query(
      `SELECT COUNT(*) FROM mcp_logs ${where}`,
      params
    );
    const total = parseInt(countResult.rows[0].count);

    // Get stats
    const statsResult = await db.query(`
      SELECT
        COUNT(*) as total,
        COUNT(*) FILTER (WHERE success = true) as success_count,
        COUNT(*) FILTER (WHERE success = false) as fail_count,
        COALESCE(ROUND(AVG(execution_time_ms)), 0) as avg_time
      FROM mcp_logs
    `);

    const stats = statsResult.rows[0];

    res.render('admin/mcp-logs/index', {
      title: 'MCP Logs',
      currentPath: '/mcp-logs',
      logs: logsResult.rows,
      total,
      limit: parseInt(limit),
      offset: parseInt(offset),
      query: req.query,
      stats,
      servers: SERVERS,
      adminUser: req.user,
      layout: 'layout'
    });
  } catch (err) {
    console.error('[MCP Logs] Route error:', err);
    res.render('admin/mcp-logs/index', {
      title: 'MCP Logs',
      currentPath: '/mcp-logs',
      logs: [],
      total: 0,
      limit: 50,
      offset: 0,
      query: {},
      stats: { total: 0, success_count: 0, fail_count: 0, avg_time: 0 },
      servers: SERVERS,
      error: err.message,
      adminUser: req.user,
      layout: 'layout'
    });
  }
});

module.exports = router;
