const jwt = require('jsonwebtoken');
require('dotenv').config();

const generateAccessToken = (userId) => {
    return jwt.sign({ id: userId }, process.env.JWT_SECRET, {
        expiresIn: process.env.JWT_EXPIRES_IN
    });
};

const generateRefreshToken = async (userId, RefreshToken) => {
    const expiryDate = new Date();
    expiryDate.setDate(expiryDate.getDate() + parseInt(process.env.REFRESH_TOKEN_EXPIRY_DAYS));
    
    const token = jwt.sign({ id: userId }, process.env.JWT_SECRET, {
        expiresIn: `${process.env.REFRESH_TOKEN_EXPIRY_DAYS}d`
    });
    
    await RefreshToken.create({
        user_id: userId,
        token: token,
        expires_at: expiryDate
    });
    
    return token;
};

const verifyToken = (token) => {
    return jwt.verify(token, process.env.JWT_SECRET);
};

module.exports = {
    generateAccessToken,
    generateRefreshToken,
    verifyToken
};