var jwt = require("jsonwebtoken");
// import asyncHandler from "express-async-handler";
// import User from "../models/userModel.js";

// const protect = asyncHandler(async (req, res, next) => {
//   let token

//   if (
//     req.headers.authorization &&
//     req.headers.authorization.startsWith('Bearer')
//   ) {
//     try {
//       token = req.headers.authorization.split(' ')[1]

//       const decoded = jwt.verify(token, process.env.JWT_SECRET)

//       req.user = await User.findById(decoded.id).select('-password')

//       next()
//     } catch (error) {
//       console.error(error)
//       res.status(401)
//       throw new Error('Not authorized, token failed')
//     }
//   }

//   if (!token) {
//     res.status(401)
//     throw new Error('Not authorized, no token')
//   }
// })

// const admin = (req, res, next) => {
//   if (req.user && req.user.isAdmin) {
//     next();
//   } else {
//     res.status(401).json({
//       message: "Not authorized as admin",
//     });
//   }
// };

const protect = (req, res, next) => {
  try {
    const token = req.headers.authorization.split(" ")[1];
    const decoded = jwt.verify(token, "pksectret");
    req.userData = decoded;
    //   console.log(req.userData)
    next();
  } catch (err) {
    return res.status(401).send({
      msg: "Your session is not valid!",
    });
  }
};

const admin = (req, res, next) => {
  if (req.userData.isAdmin === 1)
    //   console.log(req.userData)
    next();
  else {
    res.status(401).json({
      message: "Not authorized",
    });
  }
};

module.exports = { protect, admin };
