import jwt from "jsonwebtoken";
import { configDotenv } from "dotenv";
configDotenv()

const secret = process.env.JWT_SECRET;

const generateCookies = (user, res) => {
    try {
        const token = jwt.sign({ id: user.id, role: user.role, username: user.username }, secret, { expiresIn: "1d" });
        return res.cookie("token", token, {
            httpOnly: true,
            secure: false,
            sameSite: "lax"
        })
    } catch (error) {
        console.error("generateCookies error:", error);
    }
}

const verifyCookies = (req, res, next) => {
    try {
        const token = req.cookies.token;
        if(!token) return res.status(401).json({ message: "Unauthorized" });
        const decoded = jwt.verify(token, secret);
        req.username = decoded.username;
        req.id = decoded.id;
        req.role = decoded.role;
        next();
    } catch (error) {
        console.log(error)
        return res.status(500).json({ message: "Internal Server Error" });
    }
}

export { generateCookies, verifyCookies };