import jwt from "jsonwebtoken";
import HttpError from "@/helpers/http-error";
import { User } from "@/models/user";

export default async (req, res, next) => {
    try {
        const header = req.headers.authorization;
        const bearer = header?.split(" ")[1];

        if (!bearer) {
            throw new HttpError(401, "unauthorized: invalid or missing token");
        }

        const access = jwt.verify(bearer, process.env.JWT_SECRET_KEY);
        const user = (await User.findByPk(access.id))?.get({ plain: true });

        if (!user) {
            throw new HttpError(401, "unauthorized: user not found");
        }

        delete user["password"];

        Object.assign(req, { user });
        next();
    } catch (err) {
        next(err);
    }
};
