import jwt from "jsonwebtoken"
import dotenv from "dotenv"
dotenv.config()

const secret = process.env.JWT_SECRET

const generateToken = (user, res) => {
    try {
        const token = jwt.sign({ id: user._id, username: user.username }, secret, { expiresIn: "24h"})
        res.cookie("token", token, {
            httpOnly: true,
            secure: false,
            sameSite: "lax"
        })
    } catch (error) {
        console.log(error)
    }
}

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

export { generateToken, verifyToken }