#!/bin/bash

# Exit immediately if a command exits with a non-zero status
set -e

PRODUCTION_BRANCH="master"
DEVELOP_BRANCH="develop"

REMOTE_NAME=${2:-origin}
RELEASE_TYPE=$1

# 1. Check for required argument
if [ -z "$RELEASE_TYPE" ]; then
  echo "❌ Error: Must specify release type (major, minor, patch)."
  echo "Usage: ./release <type> [remote_name]"
  exit 1
fi

# 2. Verify the remote exists
if ! git remote | grep -q "^$REMOTE_NAME$"; then
  echo "❌ Error: Remote '$REMOTE_NAME' not found."
  echo "Available remotes: $(git remote | tr '\n' ' ')"
  exit 1
fi

# 3. Ensure working directory is clean (no uncommitted changes)
if [[ -n $(git status --porcelain) ]]; then
  echo "❌ Error: Your working directory is dirty. Commit or stash changes first."
  exit 1
fi

echo "🚀 Starting release on $REMOTE_NAME..."

# 4. Sync Develop
git checkout "$DEVELOP_BRANCH"
git pull "$REMOTE_NAME" "$DEVELOP_BRANCH"
npm version "$RELEASE_TYPE"
git push "$REMOTE_NAME" "$DEVELOP_BRANCH" --follow-tags

# 5. Sync Production
git checkout "$PRODUCTION_BRANCH"
git pull "$REMOTE_NAME" "$PRODUCTION_BRANCH"

# Merge develop into production locally
# Using --no-ff preserves the release history in the git graph
git merge "$DEVELOP_BRANCH" --no-edit

# 6. Push Production
git push "$REMOTE_NAME" "$PRODUCTION_BRANCH"

# 7. Return to Develop
git checkout "$DEVELOP_BRANCH"

echo "✅ Release complete!"
