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

// Google Auth Route
router.get('/google', (req, res, next) => {
    console.log('Initiating Google Auth request...');
    next();
}, passport.authenticate('google', {
    scope: ['profile', 'email'],
    session: false
}));

// Google Auth Callback
router.get('/google/callback',
    (req, res, next) => {
        console.log('Received Google Auth Callback...');
        next();
    },
    passport.authenticate('google', { session: false, failureRedirect: '/login' }),
    (req, res) => {
        console.log('Google Auth Successful. User:', req.user.email);

        // Generate JWT Token
        const token = jwt.sign({ _id: req.user._id }, process.env.JWT_SECRET, {
            expiresIn: '30d' // or match your existing expiration
        });
        console.log('JWT Token generated successfully.');

        // Redirect to frontend with token
        // Use an environment variable for CLIENT_URL if possible, otherwise assume standard localhost ports for dev
        const CLIENT_URL = process.env.CLIENT_URL || 'http://localhost:3000';
        const redirectUrl = `${CLIENT_URL}/auth/callback?token=${token}&user=${encodeURIComponent(JSON.stringify({
            _id: req.user._id,
            name: req.user.name,
            email: req.user.email,
            role: req.user.role
        }))}`;

        console.log('Redirecting to frontend:', CLIENT_URL);
        res.redirect(redirectUrl);
    }
);

module.exports = router;
