const { getSetting } = require("./settings");

function parseRoleList(value) {
  return (value || "")
    .toString()
    .split(/[,\s]+/)
    .map((item) => item.trim())
    .filter(Boolean);
}

function getRoleFlags(roles = []) {
  const adminRoleIds = parseRoleList(getSetting("discord_admin_role_id"));
  const modRoleIds = parseRoleList(getSetting("discord_mod_role_id"));
  const isAdmin = roles.some((role) => adminRoleIds.includes(role));
  const isMod = roles.some((role) => modRoleIds.includes(role));
  return { isAdmin, isMod };
}

function hasAccess(user, requiredRole) {
  if (!requiredRole || requiredRole === "public") {
    return true;
  }
  if (!user) {
    return false;
  }
  if (requiredRole === "admin") {
    return Boolean(user.isAdmin);
  }
  if (requiredRole === "mod") {
    return Boolean(user.isAdmin || user.isMod);
  }
  return false;
}

module.exports = {
  getRoleFlags,
  hasAccess
};
