#!/usr/bin/env bats

# Tests for scripts/compute-version.sh
# Invokes the real script against the real repo state.

setup() {
  REPO_ROOT="$(git rev-parse --show-toplevel)"
  SCRIPT="$REPO_ROOT/scripts/compute-version.sh"
}

@test "script exists and is executable" {
  [ -x "$SCRIPT" ]
}

@test "output matches '<upstream-tag>-seth<N>' format" {
  run "$SCRIPT"
  [ "$status" -eq 0 ]
  [[ "$output" =~ ^[0-9].+-seth[0-9]+$ ]]
}

@test "N=1 when no prior seth-tags exist" {
  # This test assumes a clean tag db. If there ARE existing seth-tags, this
  # test will report N>1 and that's the correct value. Skipped if any
  # upstream-tag-seth* tag already exists.
  upstream_tag=$(git describe --tags --abbrev=0 upstream/master)
  existing=$(git tag --list "${upstream_tag}-seth*" | wc -l)
  if [ "$existing" -gt 0 ]; then
    skip "seth-tags already exist (count=$existing); N=1 invariant only holds on first release"
  fi
  run "$SCRIPT"
  [ "$status" -eq 0 ]
  [[ "$output" == "${upstream_tag}-seth1" ]]
}

@test "N increments past existing seth-tags" {
  upstream_tag=$(git describe --tags --abbrev=0 upstream/master)
  # Create a fake seth-tag for this test, then clean up.
  fake_tag="${upstream_tag}-seth99"
  git tag "$fake_tag" 2>/dev/null || true
  run "$SCRIPT"
  git tag -d "$fake_tag" >/dev/null 2>&1 || true
  [ "$status" -eq 0 ]
  # Existing count was at least 1 (our fake), so N >= 2.
  n="${output##*-seth}"
  [ "$n" -ge 2 ]
}

@test "fails cleanly when upstream/master ref is missing" {
  # Run in a temp git repo with no upstream remote.
  tmp=$(mktemp -d)
  cd "$tmp"
  git init -q
  git commit --allow-empty -m "init" -q
  run "$SCRIPT"
  cd "$REPO_ROOT"
  rm -rf "$tmp"
  [ "$status" -ne 0 ]
}
