function normalize(value) {
  return String(value || '').trim().toLowerCase();
}

function nodeOwner(node = {}) {
  const metadataOwner = normalize(node.metadata?.ownerUserId);
  const topLevelOwner = normalize(node.userId);
  if (metadataOwner && topLevelOwner && metadataOwner !== topLevelOwner) return '';
  return metadataOwner || topLevelOwner;
}

function matchesValidatorTarget(node, target) {
  if (!node || !target) return false;
  const pcName = normalize(node.pcName || node.metadata?.hostname);
  const expectedPcName = normalize(target.pcName);
  if (!pcName || !expectedPcName || pcName !== expectedPcName) return false;
  const expectedOwner = normalize(target.owner);
  return !expectedOwner || nodeOwner(node) === expectedOwner;
}

function findValidatorTarget(topology, node) {
  return (Array.isArray(topology?.validators) ? topology.validators : [])
    .find(target => matchesValidatorTarget(node, target)) || null;
}

module.exports = { findValidatorTarget, matchesValidatorTarget, nodeOwner };
