const ADMIN_ROLE_NAMES = new Set(["Administrator", "Workspace Owner"]);
const STAFF_ROLE_NAMES = new Set(["Administrator", "Workspace Owner", "Coach", "Assistant"]);

function roleName(user) {
  return user?.app_role?.name || "";
}

function isAdministratorUser(user) {
  return ADMIN_ROLE_NAMES.has(roleName(user));
}

function isClientUser(user) {
  return roleName(user) === "Client";
}

function isStaffUser(user) {
  return STAFF_ROLE_NAMES.has(roleName(user));
}

function clientAccessWhere(user) {
  if (isAdministratorUser(user)) {
    return {};
  }

  if (isStaffUser(user)) {
    return { ownerId: user.id };
  }

  return { id: null };
}

function requireStaff(req, res, next) {
  if (!isStaffUser(req.currentUser)) {
    res.status(403).send({ error: "coach_only" });
    return;
  }

  next();
}

function authorizeCoachingRoute(req, res, next) {
  if (req.path === "/client-portal/me" || req.path.startsWith("/client-portal/")) {
    next();
    return;
  }

  requireStaff(req, res, next);
}

module.exports = {
  authorizeCoachingRoute,
  clientAccessWhere,
  isAdministratorUser,
  isClientUser,
  isStaffUser,
  requireStaff,
  roleName,
};
