import jwt from "jsonwebtoken";
import { ApiError } from "../utils/helpers.js";
import { JWT_SECRET } from "../config/env.js";

const verifyCookies = async (req, res, next) => {
    try {
        const token = req.cookies.jwt;
        if (!token) {
            throw new ApiError(401, "Unauthorized");
        }
        const decoded = await jwt.verify(token, JWT_SECRET);
        if (!decoded) {
            throw new ApiError(401, "Unauthorized");
        }

        req.username = decoded.username;
        req.role = decoded.role;
        req.id = decoded.userId;
        next();
    } catch (error) {
        if (error.statusCode) {
            return res.status(error.statusCode).send(error.message);
        }
        console.log(error);
        res.status(401).send("Unauthorized");
    }
};

export default verifyCookies;
