const express = require('express');
const router = express.Router();
const { requireTrinityAccess } = require('./middleware');
const { getMinecraftServers } = require('../../panel/discovery');
const db = require('../../database');

// Sub-routers
const playersRouter = require('./players');
const serversRouter = require('./servers');
const financialsRouter = require('./financials');
const graceRouter = require('./grace');
const auditRouter = require('./audit');
const rolesRouter = require('./roles');
const schedulerRouter = require('./scheduler');
const discordAuditRouter = require('./discord-audit');

router.use(requireTrinityAccess);

// Make CSRF token available to all admin views
router.use((req, res, next) => {
    res.locals.csrfToken = req.csrfToken();
    next();
});

router.get('/', (req, res) => {
    res.redirect('/admin/dashboard');
});

router.get('/dashboard', async (req, res) => {
    try {
        // Fetch server count from Pterodactyl
        const servers = await getMinecraftServers();
        const serversOnline = servers.length;

        // Fetch subscriber stats from database
        const { rows: subStats } = await db.query(`
            SELECT 
                COUNT(*) FILTER (WHERE status IN ('active', 'grace_period') OR is_lifetime = true) as active_count,
                COALESCE(SUM(mrr_value) FILTER (WHERE status = 'active'), 0) as mrr
            FROM subscriptions
        `);
        
        const activeSubscribers = parseInt(subStats[0]?.active_count || 0);
        const totalMRR = parseFloat(subStats[0]?.mrr || 0);

        // Fetch most recent successful sync time
        const { rows: syncRows } = await db.query(`
            SELECT MAX(last_successful_sync) as last_sync
            FROM server_sync_log
            WHERE is_online = true
        `);
        const lastSyncTime = syncRows[0]?.last_sync || null;

        res.render('admin/dashboard', { 
            title: 'Command Bridge',
            serversOnline,
            activeSubscribers,
            totalMRR,
            lastSyncTime
        });
    } catch (error) {
        console.error('Dashboard data fetch error:', error);
        // Fallback to zeros on error
        res.render('admin/dashboard', { 
            title: 'Command Bridge',
            serversOnline: 0,
            activeSubscribers: 0,
            totalMRR: 0,
            lastSyncTime: null
        });
    }
});

router.use('/players', playersRouter);
router.use('/servers', serversRouter);
router.use('/financials', financialsRouter);
router.use('/grace', graceRouter);
router.use('/audit', auditRouter);
router.use('/roles', rolesRouter);
router.use('/scheduler', schedulerRouter);
router.use('/discord', discordAuditRouter);

module.exports = router;
