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

dotenv.config()

const secretKey = process.env.SECRET_KEY


const generateToken = (user, res) => {
    try {
        const token  = jwt.sign({ id: user.id, role: user.role, username: user.username }, secretKey, { expiresIn: "30d" })
        res.cookie("token", token, { httpOnly: true, sameSite: "lax", secure: false })
    } catch (error) {
        console.log(error)
        return res.status(500).json({ message: "Internal server error" })
    }
}

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

export { generateToken, verifyToken }