#!/usr/bin/env bash
set -euo pipefail

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

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

assert_order() {
  local haystack="$1" first="$2" second="$3"
  local pos1 pos2
  pos1=$(printf '%s' "$haystack" | grep -nF "$first" | head -1 | cut -d: -f1)
  pos2=$(printf '%s' "$haystack" | grep -nF "$second" | head -1 | cut -d: -f1)
  if [ -z "$pos1" ] || [ -z "$pos2" ] || [ "$pos1" -ge "$pos2" ]; then
    echo "FAIL: expected '$first' (line $pos1) before '$second' (line $pos2)"
    echo "$haystack"
    exit 1
  fi
}

export GITHUB_SHA=abcdef1234567890
export FLIGHTS_WEB_PORT=8081

# --- swap ---
out=$("$SCRIPT" --dry-run swap)
# Order matters: tag previous before tagging current; remove old container before run new
assert_order "$out" "tag flights-web:current flights-web:previous" "tag flights-web:abcdef1 flights-web:current"
assert_contains "$out" "stop flights-web"
assert_contains "$out" "rm flights-web"
assert_order "$out" "rm flights-web" "run -d --name flights-web"
assert_contains "$out" "127.0.0.1:8081:8080"
assert_contains "$out" "flights-web:current"

# --- rollback ---
out=$("$SCRIPT" --dry-run rollback)
assert_contains "$out" "stop flights-web"
assert_contains "$out" "rm flights-web"
assert_contains "$out" "flights-web:previous"
# After running previous, current alias should be repointed
assert_order "$out" "run -d --name flights-web" "tag flights-web:previous flights-web:current"

# --- bad subcommand ---
if "$SCRIPT" --dry-run foo 2>/dev/null; then
  echo "FAIL: expected unknown subcommand to error"; exit 1
fi

echo "PASS: deploy-container.sh"
