// Pure per-connection RBAC checks for Intune tenant write-back. A connection may
// name explicit publishers (who may trigger writes) and approvers (who may
// approve change requests). Admins always pass. Empty lists mean "no extra
// restriction" — the allow_write / require_approval gates still apply.

function asList(value) {
  if (Array.isArray(value)) return value;
  try {
    const parsed = JSON.parse(value || '[]');
    return Array.isArray(parsed) ? parsed : [];
  } catch {
    return [];
  }
}

export function canPublish(connection, user) {
  if (!user) return false;
  if (user.role === 'admin') return true;
  const publishers = asList(connection?.publisher_ids ?? connection?.publisherIds);
  return publishers.length === 0 || publishers.includes(user.id);
}

export function canApprove(connection, user) {
  if (!user) return false;
  if (user.role === 'admin') return true;
  const approvers = asList(connection?.approver_ids ?? connection?.approverIds);
  return approvers.includes(user.id);
}
