#!/bin/sh
# Define colors
COLOR_SUCCESS="\033[0;32m"
COLOR_ERROR="\033[0;31m"
COLOR_IDLE="\033[0m"
COMMIT_MSG_FILE=$1
COMMIT_MSG=$(cat "$COMMIT_MSG_FILE")

# Get current branch name
BRANCH_NAME=$(git symbolic-ref --short HEAD)

# Check if the branch name matches the expected pattern
if [[ "$BRANCH_NAME" =~ ^(feature|bugfix|refactor|ci)/SID2-([0-9]+)$ ]]; then
  # Extract the prefix (feat, fix, etc.) and the ID (<SID2-{number}>)
  PREFIX=${BASH_REMATCH[1]}
  SID2_ID=${BASH_REMATCH[2]}

  # Check if the ID is exactly 5 numbers
  if [ ${#SID2_ID} -ne 5 ]; then
    echo "${COLOR_ERROR}✖ L'identifiant SID2-${SID2_ID} doit contenir exactement 5 caractères.${COLOR_IDLE}"
    exit 1
  fi

  # Determine the commit's prefix based on the branch's prefix
  case "$PREFIX" in
    feature) COMMIT_PREFIX="feat" ;;
    bugfix)  COMMIT_PREFIX="fix" ;;
    ci)      COMMIT_PREFIX="ci" ;;
    refactor) COMMIT_PREFIX="refacto" ;;
    *)
      echo "${COLOR_ERROR}✖ Le préfixe de la branche n'est pas valide. Il doit être 'feature', 'bugfix', 'ci' ou 'refactor'.${COLOR_IDLE}"
      exit 1
      ;;
  esac

  # Validating the commit message
  EXPECTED_COMMIT_MSG="^${COMMIT_PREFIX}: <SID2-${SID2_ID}> .+"
  if ! echo "$COMMIT_MSG" | grep -Eq "$EXPECTED_COMMIT_MSG"; then
    echo "🚨 Problème dans le format du message de commit : ${COLOR_ERROR} ${COMMIT_MSG} ${COLOR_IDLE}"
    echo "Format attendu : ${COLOR_SUCCESS}${COMMIT_PREFIX}: <SID2-${SID2_ID}> Description du commit${COLOR_IDLE}"
    exit 1
  fi
else
  # If the branch doesn't match the pattern, consider the commit message valid
  echo "${COLOR_SUCCESS}✅ Le message de commit est valide pour la branche '${BRANCH_NAME}'. Aucune vérification requise.${COLOR_IDLE}"
fi

exit 0

