// src/routes/oauth.js
// Discord OAuth linking flow for subscription users

const express = require('express');
const db = require('../database');
const { updateMemberDiscordId } = require('../cmsService');
const { assignDiscordRole } = require('../discordService');
const templates = require('../utils/templates');

const router = express.Router();

// 1. The entry point from the email link
router.get('/link', (req, res) => {
    const { token } = req.query;

    const tokenData = db.prepare(`
        SELECT * FROM link_tokens 
        WHERE token = ? AND used = 0 AND created_at >= datetime('now', '-1 day')
    `).get(token);

    if (!tokenData) {
        // Check if token exists but is expired or used
        const expiredToken = db.prepare('SELECT * FROM link_tokens WHERE token = ?').get(token);
        if (expiredToken && expiredToken.used === 1) {
            return res.status(400).send(templates.getUsedPage());
        }
        if (expiredToken) {
            return res.status(400).send(templates.getExpiredPage());
        }
        return res.status(400).send(templates.getInvalidPage());
    }

    const redirectUri = encodeURIComponent(`${process.env.APP_URL}/auth/callback`);
    const authUrl = `https://discord.com/api/oauth2/authorize?client_id=${process.env.DISCORD_CLIENT_ID}&redirect_uri=${redirectUri}&response_type=code&scope=identify&state=${token}`;
    
    res.redirect(authUrl);
});

// 2. The callback from Discord OAuth
router.get('/callback', async (req, res) => {
    const { code, state: token } = req.query;

    const tokenData = db.prepare('SELECT * FROM link_tokens WHERE token = ? AND used = 0').get(token);
    if (!tokenData) {
        return res.status(400).send(templates.getInvalidPage());
    }

    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}/auth/callback`,
            }),
            headers: { 'Content-Type': 'application/x-www-form-urlencoded' }
        });
        
        const oauthData = await tokenRes.json();

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

        // Update Ghost CMS with Discord ID
        await updateMemberDiscordId(tokenData.email, userData.id);

        // Assign Discord role
        const roleAssigned = await assignDiscordRole(userData.id, tokenData.tier);
        
        if (!roleAssigned) {
            // User not in server
            return res.status(400).send(templates.getNotInServerPage());
        }

        // Mark token as used
        db.prepare('UPDATE link_tokens SET used = 1 WHERE token = ?').run(token);

        console.log(`[OAuth] Successfully linked ${userData.id} to ${tokenData.email}`);
        res.send(templates.getSuccessPage());
    } catch (error) {
        console.error('[OAuth] Callback Error:', error);
        res.status(500).send(templates.getServerErrPage());
    }
});

module.exports = router;
