import jwt from "jsonwebtoken"
import dotenv from "dotenv"
dotenv.config()
const JWT_SECRET = process.env.JWT_SECRET;
if (!JWT_SECRET) {
    throw new Error("JWT_SECRET environment variable is not set");
}

// Example generateToken function (assuming user and res are provided as arguments)
const generateToken = (user, res) => {
    try {
        const token = jwt.sign(
            { _id: user._id, username: user.username },
            JWT_SECRET,
            { expiresIn: "30d" }
        );
        res.cookie("jwt", token, {
            httpOnly: true,
            sameSite: "lax",
            secure: process.env.NODE_ENV === "production"
        });
        return token;
    } catch (error) {
        console.log(error);
        res.status(500).json({ message: "Failed to generate token" });
    }
}

const verifyToken = async(req, res, next) => {
    try{
        const token = req.cookies?.jwt
        if(!token){
            return res.status(401).json({ message: "no token provided "})
        }
        const decoded = jwt.verify(token, JWT_SECRET);
        if (!decoded) {
            return res.status(401).json({ message: "invalid token "});
        }
        req.id = decoded._id;
        req.username = decoded.username;
        next();
    } catch (error) {
        console.log(error);
        res.status(401).json({ message: "invalid token "});
    }
}

export { verifyToken, generateToken }