const { eq, get } = require('lodash');

module.exports.getUsersByRoles = (relationships, roles = []) =>
  relationships
    .filter(({ edge }) => roles.includes(get(edge, 'label')))
    .map(({ node: { firstName, id, lastName, email } }) => ({
      userId: id,
      firstName,
      lastName,
      email,
      fullName: `${firstName} ${lastName}`,
    }));

module.exports.parsePersonNodeToUser = (person) => ({
  userId: person.nodeId || person.node.id,
  firstName: (person.label || person.node).firstName,
  lastName: (person.label || person.node).lastName,
  email: (person.label || person.node).email,
  fullName: `${(person.label || person.node).firstName} ${(person.label || person.node).lastName}`,
});

module.exports.hasRelationshipWithRole = (id, relationships = [], role) => {
  if (!id) {
    return false;
  }

  const roles = typeof role === 'string' ? [role] : [...role];
  return relationships
    .filter((r) => get(r, 'edge.isActive'))
    .some((r) => get(r, 'node.id') === id && roles.includes(get(r, 'edge.label')));
};

module.exports.hasAnyOfRoles = (relationships, roles) =>
  relationships.some((r) => roles.includes(r.role) || roles.includes(get(r, 'edge.label')));

module.exports.hasAnyOfTypes = (relationships, types) =>
  relationships.some((r) => types.includes(r.type) || types.includes(get(r, 'node.label')));

module.exports.hasAnyOfTypesWithRoles = (relationships, types, roles = []) =>
  relationships.some(
    (r) =>
      (types.includes(r.type) || types.includes(get(r, 'node.label'))) &&
      (roles.includes(r.role) || roles.includes(get(r, 'edge.label'))),
  );

module.exports.hasRelationship = (relationships, id) =>
  relationships.filter((r) => get(r, 'edge.isActive')).some((r) => get(r, 'node.id') === id);

module.exports.hasNodeLabel = (nodeLabel, label) => {
  if (!nodeLabel) return false;
  if (!label) return false;
  if (eq(nodeLabel, label)) return true;

  const labels = Array.isArray(nodeLabel) ? nodeLabel : nodeLabel.split('::');

  return labels.some((l) => l === label);
};
