#!/bin/bash
# -----------------------------
# Créer une branche feature ou hotfix depuis develop
# Usage:
#   ./start-branch.sh feature nom-de-ma-feature
#   ./start-branch.sh hotfix nom-du-correctif
#
# Exemples:
#   ./start-branch.sh feature login
#   ./start-branch.sh hotfix bug-cache
#
# Crée:
#   feature-login
#   hotfix-bug-cache
# -----------------------------

set -e

TYPE=$1
NAME=$2
BASE_BRANCH="develop"

if [ -z "$TYPE" ] || [ -z "$NAME" ]; then
  echo "Usage: ./start-branch.sh <feature|hotfix> <nom>"
  echo "Exemple: ./start-branch.sh feature login"
  echo "Exemple: ./start-branch.sh hotfix bug-cache"
  exit 1
fi

if [ "$TYPE" != "feature" ] && [ "$TYPE" != "hotfix" ]; then
  echo "❌ Type invalide : $TYPE"
  echo "Utilise : feature ou hotfix"
  exit 1
fi

if ! git rev-parse --is-inside-work-tree >/dev/null 2>&1; then
  echo "❌ Ce dossier n'est pas un dépôt Git."
  exit 1
fi

if [ -n "$(git status --porcelain)" ]; then
  echo "❌ Tu as des changements non commités."
  echo "Fais un commit ou un stash avant de créer une nouvelle branche."
  exit 1
fi

# Nettoyer le nom de branche
CLEAN_NAME=$(echo "$NAME" \
  | tr '[:upper:]' '[:lower:]' \
  | sed 's/[^a-z0-9._-]/-/g' \
  | sed 's/--*/-/g' \
  | sed 's/^-//' \
  | sed 's/-$//')

BRANCH_NAME="$TYPE-$CLEAN_NAME"

echo "Création de la branche : $BRANCH_NAME"
echo "Depuis : $BASE_BRANCH"
echo ""

git fetch origin

git checkout "$BASE_BRANCH"
git pull origin "$BASE_BRANCH"

if git show-ref --verify --quiet "refs/heads/$BRANCH_NAME"; then
  echo "❌ La branche locale $BRANCH_NAME existe déjà."
  exit 1
fi

if git ls-remote --exit-code --heads origin "$BRANCH_NAME" >/dev/null 2>&1; then
  echo "❌ La branche distante origin/$BRANCH_NAME existe déjà."
  exit 1
fi

git checkout -b "$BRANCH_NAME"
git push -u origin "$BRANCH_NAME"

echo ""
echo "✅ Branche créée : $BRANCH_NAME"
echo ""
echo "Tu peux développer dessus maintenant."
echo ""
echo "Quand tu as fini :"
echo "./finish-feature.sh"