const express = require('express');
const router = express.Router();
const db = require('../../database');
const { getRoleMappings } = require('../../utils/roleMappings'); // From Arbiter 3.0
const { TIER_INFO } = require('./constants');

router.get('/', (req, res) => {
    res.render('admin/roles/index', { title: 'Discord Role Audit' });
});

router.get('/mismatches', async (req, res) => {
    try {
        const client = req.app.locals.client;
        const guild = client.guilds.cache.get(process.env.GUILD_ID);
        if (!guild) throw new Error("Discord Guild not found in cache.");

        const mappings = getRoleMappings();
        
        // Reverse mappings to match TIER to ROLE ID based on your existing logic
        // Assuming your JSON maps "product-slug" -> "role_id"
        // And your webhooks mapped "product-slug" -> tier_level
        // *You may need to adapt this map based on your exact role-mappings.json structure*
        const TIER_TO_ROLE = {
            1: mappings['the-awakened'],
            5: mappings['tier-elemental'],
            10: mappings['tier-knight'],
            15: mappings['tier-master'],
            20: mappings['tier-legend'],
            105: mappings['frost-elemental'],
            // Add remaining mappings...
            499: mappings['the-sovereign']
        };

        const { rows: activeSubs } = await db.query(`
            SELECT u.discord_id, u.minecraft_username, s.tier_level
            FROM subscriptions s
            JOIN users u ON s.discord_id = u.discord_id
            WHERE s.status IN ('active', 'lifetime', 'grace_period')
        `);

        const mismatches = [];

        for (const sub of activeSubs) {
            const expectedRoleId = TIER_TO_ROLE[sub.tier_level];
            if (!expectedRoleId) continue;

            try {
                const member = await guild.members.fetch(sub.discord_id);
                const hasRole = member.roles.cache.has(expectedRoleId);
                
                if (!hasRole) {
                    mismatches.push({
                        discord_id: sub.discord_id,
                        username: sub.minecraft_username || 'Unknown',
                        tier_name: TIER_INFO[sub.tier_level]?.name || 'Unknown',
                        expected_role: expectedRoleId
                    });
                }
            } catch (err) {
                // User might have left the server
                mismatches.push({
                    discord_id: sub.discord_id,
                    username: sub.minecraft_username || 'Unknown',
                    tier_name: TIER_INFO[sub.tier_level]?.name || 'Unknown',
                    expected_role: 'User left Discord server'
                });
            }
        }

        res.render('admin/roles/_mismatches', { mismatches, layout: false });
    } catch (error) {
        console.error("Role Audit Error:", error);
        res.status(500).send("<div class='text-red-500 p-4'>Error communicating with Discord API.</div>");
    }
});

// Resync Individual
router.post('/resync/:discord_id', async (req, res) => {
    const { expected_role } = req.body;
    try {
        const client = req.app.locals.client;
        const guild = client.guilds.cache.get(process.env.GUILD_ID);
        const member = await guild.members.fetch(req.params.discord_id);
        
        await member.roles.add(expected_role);
        
        // Log it!
        await db.query(`
            INSERT INTO admin_audit_log (admin_discord_id, admin_username, action_type, target_identifier, details)
            VALUES ($1, $2, 'manual_role_assign', $3, $4)
        `, [req.user.id, req.user.username, req.params.discord_id, JSON.stringify({ assigned_role: expected_role })]);

        res.send(`<span class="text-green-500 font-bold">✅ Fixed</span>`);
    } catch (error) {
        res.send(`<span class="text-red-500 font-bold">❌ Failed</span>`);
    }
});

module.exports = router;
