const express = require('express');
const router = express.Router();
const Event = require('../models/Event');

router.get('/', async (req, res) => {
    // 1. Get current page from URL (default to page 1)
    const page = parseInt(req.query.page) || 1;
    const limit = 100; 
    const skip = (page - 1) * limit;

    // 2. Fetch data for current page and get total count
    const totalEvents = await Event.countDocuments();
    const totalPages = Math.ceil(totalEvents / limit);
    const events = await Event.find().sort({ createdAt: -1 }).skip(skip).limit(limit);

    let html = `
    <style>
      body { font-family: sans-serif; margin: 40px; background: #f4f4f9; }
      table { width: 100%; border-collapse: collapse; background: white; margin-bottom: 20px; }
      th { background: #333; color: white; text-align: left; }
      td, th { padding: 10px; border: 1px solid #ddd; font-size: 14px; }
      tr:nth-child(even) { background: #f9f9f9; }
      tr.anomaly td { background: #ffe6e6 !important; color: #cc0000 !important; font-weight: bold !important; }
      
      
      /* Pagination Styling */
      .pagination { display: flex; gap: 10px; align-items: center; font-size: 14px; }
      .pagination a { padding: 8px 16px; border: 1px solid #ddd; background: white; color: #333; text-decoration: none; border-radius: 4px; }
      .pagination a.active { background: #333; color: white; border-color: #333; }
      .pagination a.disabled { color: #ccc; pointer-events: none; border-color: #eee; }
    </style>

    <h2>Email Access Logs (${totalEvents} total entries)</h2>
    <table>
      <tr>
        <th>Time</th>
        <th>User</th>
        <th>Device</th>
        <th>Country</th>
        <th>Time Bucket</th>
        <th>Risk</th>
        <th>Reasons</th>
        <th>Anomaly</th>
      </tr>
    `;

    events.forEach(e => {
        html += `
        <tr class="${e.isAnomalous ? 'anomaly' : ''}">
            <td>${e.createdAt}</td>
            <td>${e.userId ? e.userId.substring(0, 8) + "..." : "N/A"}</td>
            <td>${e.userAgentCategory}</td>
            <td>${e.country}</td>
            <td>${e.timeBucket}</td>
            <td>${e.riskScore}</td>
            <td>${(e.reasons || []).join(", ")}</td>
            <td>${e.isAnomalous ? '⚠️ YES' : 'NO'}</td>
        </tr>
        `;
    });

    html += "</table>";

    // 3. Append Pagination Controls
    html += `<div class="pagination">`;
    if (page > 1) {
        html += `<a href="?page=${page - 1}">« Previous</a>`;
    } else {
        html += `<a class="disabled">« Previous</a>`;
    }

    for (let i = 1; i <= totalPages; i++) {
        html += `<a href="?page=${i}" class="${page === i ? 'active' : ''}">${i}</a>`;
    }

    if (page < totalPages) {
        html += `<a href="?page=${page + 1}">Next »</a>`;
    } else {
        html += `<a class="disabled">Next »</a>`;
    }
    html += `</div>`;

    res.send(html);
});

module.exports = router;
