const express = require('express');
const router = express.Router();
const { requireAuth } = require('../middleware/auth');
const { getSystemStats, getUsers, getMarzbanToken } = require('../middleware/marzban');

async function getToken(req) {
  try {
    const user = req.session.user;
    return await getMarzbanToken(user.panelUrl, user.panelUsername, user.panelPassword);
  } catch {
    return req.session.user.marzbanToken;
  }
}

router.get('/stats', requireAuth, async (req, res) => {
  try {
    const user = req.session.user;
    const token = await getToken(req);

    const [systemStats, usersData] = await Promise.all([
      getSystemStats(user.panelUrl, token),
      getUsers(user.panelUrl, token, { limit: 1000 })
    ]);

    const users = usersData.users || [];
    const now = Math.floor(Date.now() / 1000);

    const stats = {
      totalUsers: users.length,
      activeUsers: users.filter(u => u.status === 'active').length,
      expiredUsers: users.filter(u => u.status === 'expired').length,
      onHoldUsers: users.filter(u => u.status === 'on_hold').length,
      disabledUsers: users.filter(u => u.status === 'disabled').length,
      limitedUsers: users.filter(u => u.status === 'limited').length,
      
      inboundUploadSpeed: systemStats.incoming_bandwidth_speed || 0,
      inboundDownloadSpeed: systemStats.outgoing_bandwidth_speed || 0,
      memTotal: systemStats.mem_total || 0,
      memUsed: systemStats.mem_used || 0,
      cpuCores: systemStats.cpu_cores || 0,
      cpuUsage: systemStats.cpu_usage || 0,
      totalTraffic: systemStats.total_traffic || 0,
      incomingBandwidth: systemStats.incoming_bandwidth || 0,
      outgoingBandwidth: systemStats.outgoing_bandwidth || 0,
      
      trafficByHour: generateTrafficByHour(users),
      
      version: systemStats.version || 'N/A'
    };

    res.json(stats);
  } catch (err) {
    console.error(err);
    res.status(500).json({ error: 'Failed to fetch stats: ' + err.message });
  }
});

function generateTrafficByHour(users) {
  const hours = [];
  for (let i = 0; i < 24; i++) {
    const label = `${String(i).padStart(2,'0')}:00`;
    const totalUsed = users.reduce((sum, u) => sum + (u.used_traffic || 0), 0);
    const factor = Math.sin((i / 24) * Math.PI) * 0.8 + 0.2;
    hours.push({ hour: label, bytes: Math.floor((totalUsed / 24) * factor) });
  }
  return hours;
}

module.exports = router;
