import jwt from "jsonwebtoken";
import dotenv from "dotenv"

dotenv.config()

const secret = process.env.SECRET_KEY || "default-secret-key";

const generateToken = (user, res) => {
    try {
        const token = jwt.sign({ username: user.username, role: user.role, id: user._id }, secret, { expiresIn: "3h" });
        res.cookie("jwt", token, { httpOnly: true, secure: false, sameSite: "lax"})
    } catch (error) {
        console.error("Error generating token:", error);
        return res.status(500).json({ message: "Error generating token" });
    }
}

const verifyToken = (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, secret);
        req.user = decoded;
        next();
    } catch (error) {
        console.error("Error verifying token:", error);
        return res.status(401).json({ message: "Invalid token" });
    }
}

export { generateToken, verifyToken };