require("dotenv").config();
const db = require("../../models");
const jwt = require("jsonwebtoken");

exports.authMiddleware = (roles = []) => {
  return async (req, res, next) => {
    try {
      let token = req.header("Authorization");

      if (!token) {
        console.log("No token provided");
        return res.status(401).json({ message: "Unauthorized" });
      }

      if (!token.startsWith("Bearer ")) {
        console.log("Invalid token format");
        return res.status(401).json({ message: "Unauthorized" });
      }

      token = token.substring(7);
      const decoded = jwt.verify(token, process.env.JWT_pa);

      // console.log("Decoded token:", decoded);
      const user = await db.users.findOne({
        where: { id: decoded.id },
        raw: true,
      });

      if (!user) {
        console.log("User not found");
        return res.status(401).json({ message: "Unauthorized" });
      }

      if (roles.length && (!roles.includes(user.role) && !roles.includes(user.second_role))) {
          console.log("User role not permitted:", user.role, user.second_role);
          console.log("User role not permitted:", roles);
          return res.status(403).json({ message: "Unauthorized" });
      }

      req.user = user;
      next();
    } catch (error) {
      console.error("Auth Middleware Error:", error.message);
      res.status(401).json({ message: "Unauthorized" });
    }
  };
};