import jwt from "jsonwebtoken";
import RetailDistributor from "../resources/RetailDistributor/RetailDistributorModel.js";

// import { Business } from "../resources/Businesses/BusinessModel.js";

export const isAuthenticatedRD = async (req, res, next) => {
  try {
    if (!req.headers.authorization) {
      return res.status(400).json({
        success: false,
        message: "Login to Access this resource",
      });
    }
    const getToken = req.headers;

    // console.log(getToken);
    //remove Bearer from token
    const fronttoken = getToken.authorization.slice(7);

    const frontdecoded = jwt.verify(fronttoken, process.env.JWT_SECRET);
    if (!frontdecoded) {
      return res.status(400).json({
        success: false,
        message: "incorrect token",
      });
    }

    const fuser = await RetailDistributor.findById(frontdecoded._id);
    // console.log(fuser);
    req.user = fuser;

    next();
  } catch (error) {
    return res.status(400).json({
      success: false,
      message: error.message,
    });
  }
};
