#!/usr/bin/env bash
# Test: scripts/ci/notify-telegram.sh in --dry-run mode emits the right payloads.
set -euo pipefail

SCRIPT="$(cd "$(dirname "$0")/../.." && pwd)/scripts/ci/notify-telegram.sh"
[ -x "$SCRIPT" ] || { echo "FAIL: $SCRIPT not executable"; exit 1; }

# Required env for non-dry-run; test still sets them so the script doesn't bail early.
export TELEGRAM_BOT_TOKEN="test-token"
export TELEGRAM_CHAT_ID="123"
export GITHUB_REPOSITORY="gnezim/flights-web"
export GITHUB_RUN_ID="42"
export GITHUB_SERVER_URL="https://git.gnerim.ru"
export GITHUB_SHA="abc1234567890"
export GITHUB_WORKFLOW="ci-deploy"

assert_contains() {
  local haystack="$1" needle="$2"
  case "$haystack" in
    *"$needle"*) ;;
    *) echo "FAIL: expected to find '$needle' in:"; echo "$haystack"; exit 1 ;;
  esac
}

# --- start ---
out=$("$SCRIPT" --dry-run start ci-deploy)
assert_contains "$out" "🚀 ci-deploy started"
assert_contains "$out" "abc1234"
assert_contains "$out" "https://git.gnerim.ru/gnezim/flights-web/actions/runs/42"

# --- ok ---
out=$("$SCRIPT" --dry-run ok ci-deploy)
assert_contains "$out" "✅ ci-deploy passed"

# --- fail with extra context ---
out=$("$SCRIPT" --dry-run fail ci-deploy "Run Playwright e2e")
assert_contains "$out" "❌ ci-deploy FAILED"
assert_contains "$out" "Run Playwright e2e"

# --- missing env in non-dry-run: should skip cleanly (exit 0, log to stderr) ---
unset TELEGRAM_BOT_TOKEN
set +e
err=$("$SCRIPT" ok ci-deploy 2>&1 >/dev/null)
rc=$?
set -e
if [ $rc -ne 0 ]; then
  echo "FAIL: expected exit 0 when TELEGRAM_BOT_TOKEN missing (got $rc)"
  exit 1
fi
assert_contains "$err" "skipping"
export TELEGRAM_BOT_TOKEN="test-token"


# --- fail with log tail ---
TMPLOG=$(mktemp)
printf 'line1\nline2\nline3\n' > "$TMPLOG"
out=$("$SCRIPT" --dry-run fail ci-deploy "Run Playwright e2e" "$TMPLOG")
assert_contains "$out" "last 3 lines"
assert_contains "$out" "line1"
assert_contains "$out" "line3"
rm -f "$TMPLOG"

# --- fail with missing log file: should still print message, no crash ---
out=$("$SCRIPT" --dry-run fail ci-deploy "Build" "/nonexistent/log")
assert_contains "$out" "❌ ci-deploy FAILED"

echo "PASS: notify-telegram.sh"
