require('dotenv').config();
const express = require('express');
const axios = require('axios');
const cors = require('cors');
const path = require('path');

const app = express();
app.use(cors());
app.use(express.json());

// Servir frontend
app.use(express.static(path.join(__dirname, '../public')));

// Rota de autenticação do Discord
app.post('/api/discord-auth', async (req, res) => {
    const { code } = req.body;

    const params = new URLSearchParams({
        client_id: process.env.CLIENT_ID,
        client_secret: process.env.CLIENT_SECRET,
        grant_type: 'authorization_code',
        code,
        redirect_uri: process.env.REDIRECT_URI,
        scope: 'identify guilds guilds.members.read'
    });

    try {
        const response = await axios.post('https://discord.com/api/oauth2/token', params, {
            headers: { 'Content-Type': 'application/x-www-form-urlencoded' }
        });

        res.json({ access_token: response.data.access_token });
    } catch (error) {
        res.status(400).json({ error: 'Falha ao autenticar com Discord.' });
    }
});

app.get('/auth/callback', async (req, res) => {
    const code = req.query.code;
    if (!code) return res.send('Código não encontrado.');
  
    const params = new URLSearchParams({
      client_id: process.env.CLIENT_ID,
      client_secret: process.env.CLIENT_SECRET,
      grant_type: 'authorization_code',
      code,
      redirect_uri: process.env.REDIRECT_URI,
      scope: 'identify guilds guilds.members.read'
    });
  
    try {
      const response = await axios.post('https://discord.com/api/oauth2/token', params, {
        headers: { 'Content-Type': 'application/x-www-form-urlencoded' }
      });
  
      const token = response.data.access_token;
  
      const userInfo = await axios.get('https://discord.com/api/users/@me', {
        headers: { Authorization: `Bearer ${token}` }
      });
  
      res.redirect('/index.html'); // se seu dashboard estiver em "public/dashboard.html"
    } catch (err) {
      console.error(err.response?.data || err.message);
      res.status(500).send('Erro ao autenticar com o Discord.');
    }
  });
  

const PORT = process.env.PORT || 3000;
app.listen(PORT, () => console.log(`Servidor rodando na porta ${PORT}`));
