#!/usr/bin/env bash

set -euo pipefail

NPM_REGISTRY="${NPM_REGISTRY:-https://registry.npmjs.org/}"
PACKAGE_NAME="$(node -p "require('./package.json').name")"
PACKAGE_VERSION="$(node -p "require('./package.json').version")"

echo "Preparing to publish ${PACKAGE_NAME}@${PACKAGE_VERSION} to ${NPM_REGISTRY}"

if ! PUBLISH_USER="$(npm whoami --registry "${NPM_REGISTRY}" 2>/dev/null)"; then
  echo "npm authentication failed for ${NPM_REGISTRY}."
  echo "Run: npm login --registry ${NPM_REGISTRY}"
  echo "If you use an access token, update ~/.npmrc with a valid token that can publish ${PACKAGE_NAME}."
  exit 1
fi

echo "Authenticated as ${PUBLISH_USER}"

if PACKAGE_MAINTAINERS_JSON="$(npm view "${PACKAGE_NAME}" maintainers --json --registry "${NPM_REGISTRY}" 2>/dev/null)"; then
  if ! node -e '
    const user = process.argv[1];
    const maintainers = JSON.parse(process.argv[2]);
    const list = Array.isArray(maintainers) ? maintainers : [maintainers];
    const names = list.map((item) => typeof item === "string" ? item.split(" <")[0] : item?.name).filter(Boolean);
    process.exit(names.includes(user) ? 0 : 1);
  ' "${PUBLISH_USER}" "${PACKAGE_MAINTAINERS_JSON}"; then
    EXISTING_MAINTAINERS="$(node -e '
      const maintainers = JSON.parse(process.argv[1]);
      const list = Array.isArray(maintainers) ? maintainers : [maintainers];
      const values = list.map((item) => typeof item === "string" ? item : `${item.name} <${item.email || ""}>`).filter(Boolean);
      console.log(values.join(", "));
    ' "${PACKAGE_MAINTAINERS_JSON}")"
    echo "Authenticated as ${PUBLISH_USER}, but that account cannot publish ${PACKAGE_NAME}."
    echo "Existing maintainers: ${EXISTING_MAINTAINERS}"
    echo "Use the maintainer account or run: npm owner add ${PUBLISH_USER} ${PACKAGE_NAME}"
    exit 1
  fi
fi
## npm login --registry https://registry.npmjs.org/
yarn build

npm publish --registry "${NPM_REGISTRY}" --access public
