const {
  isSellerHasFeatureFlag,
  isUserHasPermissionToDoAction,
} = require("../helpers/common");

const checkPermissionMiddleware = (module, action) => {
  return async (req, res, next) => {
    try {
      const { seller_account_id } = req;
      const hasFeatureFlag = await isSellerHasFeatureFlag(req);

      if (hasFeatureFlag) {
        const isPermitted = await isUserHasPermissionToDoAction(
          action,
          module,
          seller_account_id
        );

        if (!isPermitted) {
          return res
            .status(200)
            .json({ success: false, message: "Not Authorized" });
        }
      }

      next();
    } catch (error) {
      console.error("Middleware error:", error);
      return res.status(500).json({ success: false, message: "Server Error" });
    }
  };
};

module.exports = checkPermissionMiddleware;
