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

/**
 * Standard Discord OAuth - redirects to admin after login
 */
router.get('/discord', (req, res, next) => {
  // Check if there's a checkout tier to pass through
  const tier = req.session.pendingCheckoutTier;
  
  passport.authenticate('discord', {
    state: tier ? `checkout:${tier}` : undefined
  })(req, res, next);
});

router.get('/discord/callback', passport.authenticate('discord', {
  failureRedirect: '/'
}), (req, res) => {
  // Check for checkout flow via state parameter
  const state = req.query.state;
  
  if (state && state.startsWith('checkout:')) {
    const tierLevel = state.replace('checkout:', '');
    // Clear any session data
    delete req.session.pendingCheckoutTier;
    
    // Redirect to checkout creation with Discord ID now available
    return res.redirect(`/stripe/checkout?tier=${tierLevel}`);
  }
  
  // Standard admin redirect
  res.redirect('/admin');
});

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

module.exports = router;
