const User = require('../models/user');
const bcrypt = require('bcryptjs');
const jwt = require('jsonwebtoken');

// Login user
exports.login = async (req, res) => {
    try {
        const { username, password } = req.body;

        // 1️⃣ Check if user exists
        const user = await User.findOne({ username });
        if (!user) {
            return res.status(400).json({ message: 'Invalid email or password' });
        }

        // 2️⃣ Compare passwords
        const isMatch = await bcrypt.compare(password, user.password);
        if (!isMatch) {
            return res.status(400).json({ message: 'Invalid email or password' });
        }

        // 3️⃣ Generate JWT token
        const accessToken = jwt.sign(
            { userId: user._id },
            process.env.JWT_SECRET || 'csc491_access_secret', // Use a secret key from env
            { expiresIn: '1h' } // Token expires in 1 hour
        );

        const refreshToken = jwt.sign(
            { userId: user._id },
            process.env.JWT_REFRESH || 'csc491_refresh_secret', // Use a secret key from env
        );

        user.refresh_token = refreshToken;
        await user.save();

        // 4️⃣ Send response with token
        res.status(200).json({ 
            message: 'Login successful', 
            accessToken,
            refreshToken,
            user: { id: user._id, username: user.username, email: user.email } 
        });

    } catch (error) {
        res.status(500).json({ message: 'Server error', error: error.message });
    }
};

exports.refreshToken = async (req, res) => {
    try {
        const { refreshToken } = req.body;

        if (!refreshToken) {
            return res.status(400).json({ message: 'Refresh token is required' });
        }

        jwt.verify(refreshToken, process.env.JWT_REFRESH || 'csc491_refresh_secret', async (err, u) => {
            if (err) {
                return res.status(403).json({ message: 'Invalid refresh token' });
            }

            const user = await User.findById(u.userId);
            if (!u || u.refresh_token !== refreshToken) {
                return res.status(403).json({ message: 'User not found' });
            }

            const newAccessToken = jwt.sign(
                { userId: u._id },
                process.env.JWT_SECRET || 'csc491_access_secret', // Use a secret key from env
                { expiresIn: '1h' } // Token expires in 1 hour
            );

            res.status(200).json({ accessToken: newAccessToken });
        }
        );
    } catch (error) {
        res.status(500).json({ message: 'Server error', error: error.message });
    }
};

exports.logout = async (req, res) => {
    try {
        const { userId } = req.user;

        await User.findByIdAndUpdate(userId, { refresh_token: '' });

        res.status(200).json({ message: 'Logout successful' });
    } catch (error) {
        res.status(500).json({ message: 'Server error', error: error.message });
    }
};