import { Router } from 'express';
import { env } from '../../config/env';

const router = Router();

const baseUrl = () => {
  const origin = env.publicBaseUrl || `http://localhost:${env.port}`;
  const path = env.webBasePath || '/ucp';
  return `${origin}${path}`;
};

router.get('/discord', (_req, res) => {
  const redirect = encodeURIComponent(`${baseUrl()}/auth/callback`);
  const url =
    `https://discord.com/api/oauth2/authorize?client_id=${env.clientId}` +
    `&redirect_uri=${redirect}&response_type=code&scope=identify%20guilds`;
  res.redirect(url);
});

router.get('/callback', async (req, res) => {
  const code = req.query.code;
  if (!code) return res.status(400).send('No code provided');
  if (!env.clientSecret) return res.status(500).send('Missing DISCORD_CLIENT_SECRET');

  try {
    const params = new URLSearchParams({
      client_id: env.clientId,
      client_secret: env.clientSecret,
      grant_type: 'authorization_code',
      code: String(code),
      redirect_uri: `${baseUrl()}/auth/callback`
    });

    const tokenRes = await fetch('https://discord.com/api/oauth2/token', {
      method: 'POST',
      headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
      body: params
    });

    if (!tokenRes.ok) {
      const errText = await tokenRes.text();
      return res.status(500).send(`Token exchange failed: ${errText}`);
    }

    const token = await tokenRes.json();
    const authHeader = { Authorization: `Bearer ${token.access_token}` };
    const [userRes, guildRes] = await Promise.all([
      fetch('https://discord.com/api/users/@me', { headers: authHeader }),
      fetch('https://discord.com/api/users/@me/guilds', { headers: authHeader })
    ]);

    const user = await userRes.json();
    const guilds = await guildRes.json();

    req.session.user = user;
    req.session.guilds = guilds;
    req.session.token = {
      access_token: token.access_token,
      refresh_token: token.refresh_token,
      expires_at: Date.now() + (token.expires_in ?? 0) * 1000
    };

    const basePath = env.webBasePath || '/ucp';
    req.session.save(() => res.redirect(`${basePath}/dashboard`));
  } catch (err) {
    res.status(500).send('OAuth failed');
  }
});

router.get('/logout', (req, res) => {
  const basePath = env.webBasePath || '/ucp';
  req.session?.destroy(() => res.redirect(`${basePath || '/'}`));
});

export default router;
