#!/bin/sh

# Get the current branch
current_branch=$(git rev-parse --abbrev-ref HEAD)

# Define the protected branch
protected_branch="main"

echo "Running pre-commit checks..."

run_check() {
  label="$1"
  shift
  start_time=$(node -p "Date.now()")

  if output=$("$@" 2>&1); then
    elapsed_ms=$(($(node -p "Date.now()") - start_time))
    printf '%s passed in %d.%03ds.\n' "$label" "$((elapsed_ms / 1000))" "$((elapsed_ms % 1000))"
  else
    printf '%s\n' "$output"
    elapsed_ms=$(($(node -p "Date.now()") - start_time))
    printf '%s failed after %d.%03ds.\n' "$label" "$((elapsed_ms / 1000))" "$((elapsed_ms % 1000))"
    return 1
  fi
}

run_format_check() {
  run_check "Formatting" pnpm run format:check
}

# Check if the current branch is the protected branch
if [ "$current_branch" = "$protected_branch" ]; then
  echo "🚨 You are about to commit to the $protected_branch branch. Are you sure? (y/n)"
  read -r answer </dev/tty
  if [ "$answer" != "${answer#[Yy]}" ]; then
    # Commit approved, run checks
    run_format_check
  else
    echo "Commit to $protected_branch branch has been canceled."
    exit 1 # Commit will be blocked
  fi
fi

# If not the protected branch, run checks
run_format_check
