// src/routes/adminAuth.js
// Discord OAuth authentication for admin panel access

const express = require('express');
const router = express.Router();

// Admin login - redirect to Discord OAuth
router.get('/login', (req, res) => {
    const redirectUri = encodeURIComponent(`${process.env.APP_URL}/admin/callback`);
    res.redirect(`https://discord.com/api/oauth2/authorize?client_id=${process.env.DISCORD_CLIENT_ID}&redirect_uri=${redirectUri}&response_type=code&scope=identify`);
});

// OAuth callback - set session and redirect to dashboard
router.get('/callback', async (req, res) => {
    const { code } = req.query;
    
    try {
        // Exchange code for Discord access token
        const tokenRes = await fetch('https://discord.com/api/oauth2/token', {
            method: 'POST',
            body: new URLSearchParams({
                client_id: process.env.DISCORD_CLIENT_ID,
                client_secret: process.env.DISCORD_CLIENT_SECRET,
                code,
                grant_type: 'authorization_code',
                redirect_uri: `${process.env.APP_URL}/admin/callback`,
            }),
            headers: { 'Content-Type': 'application/x-www-form-urlencoded' }
        });
        const tokenData = await tokenRes.json();

        // Get Discord user profile
        const userRes = await fetch('https://discord.com/api/users/@me', {
            headers: { authorization: `Bearer ${tokenData.access_token}` },
        });
        const userData = await userRes.json();

        // Set session
        req.session.discordId = userData.id;
        
        console.log(`[Admin Auth] ${userData.username} logged in`);
        res.redirect('/admin');
    } catch (error) {
        console.error('[Admin Auth] Login failed:', error);
        res.status(500).send('Admin login failed. Please try again.');
    }
});

// Logout - destroy session
router.get('/logout', (req, res) => {
    req.session.destroy();
    res.redirect('/');
});

module.exports = router;
