#!/bin/bash
set -euo pipefail

# Load only what this script needs from .env (full-file export breaks on
# values with spaces/special chars, and with set -e it aborts immediately)
if [ -z "${NPM_PUBLISH_TOKEN:-}" ] && [ -f .env ]; then
  # grep exits 1 when the key is missing. With set -o pipefail that status
  # becomes the assignment's status, and set -e aborts before the login prompt.
  NPM_PUBLISH_TOKEN=$(grep -E '^[[:space:]]*NPM_PUBLISH_TOKEN=' .env | tail -n1 | cut -d= -f2- | sed -e 's/^[[:space:]]*//' -e 's/[[:space:]]*$//' -e 's/^"//' -e 's/"$//' -e "s/^'//" -e "s/'$//" || true)
  export NPM_PUBLISH_TOKEN
fi

# Get curent branch name
current_branch=$(git rev-parse --abbrev-ref HEAD)
GIT_REMOTE=$(git config --get branch.$current_branch.remote)

REMOTE="${GIT_REMOTE:-tiledesk-server}"

# Check if the token is set
if [ -z "${NPM_PUBLISH_TOKEN:-}" ]; then
  echo "⚠️ Missing NPM_PUBLISH_TOKEN in environment."
  echo "You can speed up the process by setting the environment variable with your publish token."
  read -p "Do you want to continue with manual login? (y/n): " choice
  if [[ "$choice" != "y" && "$choice" != "Y" ]]; then
    echo "❌ Deploy aborted."
    exit 1
  else
    echo "💡 Proceed with 'npm login' manually..."
    npm login
  fi
else
  # Create temporary .npmrc with the token
  echo "//registry.npmjs.org/:_authToken=${NPM_PUBLISH_TOKEN}" > ~/.npmrc
fi

git pull

# Determine version bump type (default: patch)
VERSION_TYPE="${1:-patch}"

# Validate version type
if [[ "$VERSION_TYPE" != "patch" && "$VERSION_TYPE" != "minor" && "$VERSION_TYPE" != "major" ]]; then
  echo "❌ Invalid version type: $VERSION_TYPE"
  echo "Usage: ./deploynew.sh [patch|minor|major]"
  echo "Default: patch (if no argument provided)"
  exit 1
fi

echo "📦 Bumping version: $VERSION_TYPE"
# --force: allow bump with local uncommitted changes (e.g. this script).
# npm version still only commits package.json / lockfile.
npm version "$VERSION_TYPE" --force
version=$(node -e 'console.log(require("./package.json").version)')
echo "version $version"

if [ -z "$version" ]; then
  echo "❌ Could not read version from package.json"
  exit 1
fi

# npm version already creates tag v$version; also create $version for Docker workflows
if ! git rev-parse -q --verify "refs/tags/$version" >/dev/null; then
  git tag -a "$version" -m "$(git log -1 --format=%s)"
  echo "Created a new tag, $version"
else
  echo "Tag $version already exists"
fi

# Push branch first, then ONLY this release's tags (never git push --tags:
# it can fail on unrelated local tags or send a huge pack → HTTP 400)
echo "🚀 Pushing branch and release tags to $REMOTE..."
git push "$REMOTE" HEAD
git push "$REMOTE" "refs/tags/$version" "refs/tags/v$version"

npm publish --access public

# Remove temporary .npmrc if created
if [ -f ~/.npmrc ]; then
  rm ~/.npmrc
fi

echo "🎉 Deploy completed!"