const express = require('express');
const router = express.Router();
const db = require('../../database');

// Shell route
router.get('/', (req, res) => {
    res.render('admin/appeals/index', { title: 'Trinity Appeals' });
});

// HTMX polling endpoint
router.get('/list', async (req, res) => {
    try {
        const { rows: appeals } = await db.query(`
            SELECT id, discord_username, email, circumstances, requested_outcome,
                   status, trinity_notes, actioned_by, actioned_at, created_at
            FROM trinity_appeals
            ORDER BY
                CASE status
                    WHEN 'pending' THEN 1
                    WHEN 'needs_info' THEN 2
                    WHEN 'approved' THEN 3
                    WHEN 'denied' THEN 4
                END,
                created_at DESC
            LIMIT 100;
        `);

        const counts = {
            pending: appeals.filter(a => a.status === 'pending').length,
            needs_info: appeals.filter(a => a.status === 'needs_info').length,
            approved: appeals.filter(a => a.status === 'approved').length,
            denied: appeals.filter(a => a.status === 'denied').length,
            total: appeals.length
        };

        res.render('admin/appeals/_list', { appeals, counts, layout: false });
    } catch (error) {
        console.error('Appeals list error:', error);
        res.status(500).send("<tr><td colspan='6' class='text-center text-red-500'>Error loading appeals.</td></tr>");
    }
});

// Shared action handler: approve / deny / needs_info
async function actionAppeal(req, res, newStatus, label, colorClass) {
    const { id } = req.params;
    const notes = (req.body && req.body.notes) ? String(req.body.notes).slice(0, 2000) : null;
    const adminId = req.user.id;
    const adminUsername = req.user.username;

    const client = await db.pool.connect();
    try {
        await client.query('BEGIN');

        const { rowCount } = await client.query(`
            UPDATE trinity_appeals
            SET status = $1,
                trinity_notes = COALESCE($2, trinity_notes),
                actioned_by = $3,
                actioned_at = NOW()
            WHERE id = $4
        `, [newStatus, notes, adminUsername, id]);

        if (rowCount === 0) {
            await client.query('ROLLBACK');
            return res.status(404).send(`<span class="text-red-500 font-bold text-sm">❌ Not found</span>`);
        }

        await client.query(`
            INSERT INTO admin_audit_log (admin_discord_id, admin_username, action_type, target_identifier, details)
            VALUES ($1, $2, $3, $4, $5)
        `, [adminId, adminUsername, `appeal_${newStatus}`, `appeal:${id}`, JSON.stringify({ notes: notes || null })]);

        await client.query('COMMIT');
        res.send(`<span class="${colorClass} font-bold text-sm">✅ ${label}</span>`);
    } catch (error) {
        await client.query('ROLLBACK');
        console.error(`Appeal ${newStatus} error:`, error);
        res.status(500).send(`<span class="text-red-500 font-bold text-sm">❌ Error</span>`);
    } finally {
        client.release();
    }
}

router.post('/:id/approve', (req, res) => actionAppeal(req, res, 'approved', 'Approved', 'text-green-500'));
router.post('/:id/deny',    (req, res) => actionAppeal(req, res, 'denied',   'Denied',   'text-red-500'));
router.post('/:id/info',    (req, res) => actionAppeal(req, res, 'needs_info','Info Requested','text-yellow-500'));
router.post('/:id/reopen',  (req, res) => actionAppeal(req, res, 'pending',  'Reopened', 'text-gray-500'));

module.exports = router;
