// src/routes/admin.js
// Admin panel routes for manual role assignment and audit logs

const express = require('express');
const path = require('path');
const router = express.Router();
const { requireAdmin } = require('../middleware/auth');
const db = require('../database');
const { assignDiscordRole, removeAllSubscriptionRoles, rolesConfig } = require('../discordService');
const { findMemberByEmail } = require('../cmsService');

// Apply admin protection to all routes
router.use(requireAdmin);

// 1. Render the admin UI
router.get('/', (req, res) => {
    res.sendFile(path.join(__dirname, '../views/admin.html'));
});

// 2. Get tier list for dropdown population
router.get('/api/tiers', (req, res) => {
    res.json(rolesConfig);
});

// 3. Search API endpoint - find user by email
router.get('/api/search', async (req, res) => {
    const { email } = req.query;
    try {
        const cmsUser = await findMemberByEmail(email);
        res.json(cmsUser);
    } catch (error) {
        console.error('[Admin] Search failed:', error);
        res.status(404).json({ error: 'User not found' });
    }
});

// 4. Manual role assignment endpoint
router.post('/api/assign', async (req, res) => {
    const { targetDiscordId, action, tier, reason } = req.body;
    const adminId = req.session.discordId;

    try {
        if (action === 'add') {
            await assignDiscordRole(targetDiscordId, tier);
        } else if (action === 'remove_all') {
            await removeAllSubscriptionRoles(targetDiscordId);
        }

        // Log the action to audit log
        const stmt = db.prepare(`
            INSERT INTO audit_logs (admin_id, target_user, action, reason) 
            VALUES (?, ?, ?, ?)
        `);
        stmt.run(adminId, targetDiscordId, `${action}_${tier || 'all'}`, reason);

        console.log(`[Admin] ${adminId} performed ${action} on ${targetDiscordId}`);
        res.json({ success: true, message: 'Action completed and logged.' });
    } catch (error) {
        console.error('[Admin] Assignment failed:', error);
        res.status(500).json({ error: error.message });
    }
});

// 5. Audit log retrieval endpoint
router.get('/api/audit-log', async (req, res) => {
    try {
        const stmt = db.prepare(`
            SELECT * FROM audit_logs 
            ORDER BY timestamp DESC LIMIT 50
        `);
        const logs = stmt.all();
        res.json(logs);
    } catch (error) {
        console.error('[Admin] Failed to fetch audit logs:', error);
        res.status(500).json({ error: 'Failed to fetch logs' });
    }
});

module.exports = router;
