import jwt from 'jsonwebtoken';
import bcrypt from 'bcryptjs';
import dotenv from 'dotenv';

dotenv.config();

const secret = process.env.JWT_SECRET;


const generateToken = (user, res) => {
    try {
        const payload = {
            user_id: user.user_id,
            email: user.email
        };
        const token = jwt.sign(payload, secret, { expiresIn: '30d' });
        res.cookie('token', token, { maxAge: 900000, httpOnly: true, secure: false, sameSite: "lax" });
        return token;
    } catch (err) {
        console.log(err);
    }
}

const verifyToken = (req, res, next) => {
    try {
        const token = req.cookies.token;
        if (!token) return res.status(401).json({ message: 'No token provided' });
        jwt.verify(token, secret, (err, decoded) => {
            if (err) return res.status(401).json({ message: 'Invalid token' });
            req.user = decoded;
            next();
        });
    } catch (err) {
        console.log(err);
    }
}

export { generateToken, verifyToken };