#!/usr/bin/env bash
# pr-merge must forward --no-ci-expected to the queue guard, and only then.
# The flag is the sanctioned merge path for a repository with no CI configured
# (see test-ci-queue-wait-no-ci-expected.sh for the guard-side semantics);
# this harness pins only the pass-through: present when requested, absent when
# not, with the rest of the guard invocation unchanged.

set -euo pipefail

SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
WORK_DIR="${MOSAIC_TEST_WORK_DIR:-$PWD/.mosaic-test-work/pr-merge-no-ci-expected}"
FIXTURE_DIR="$WORK_DIR/tools/git"
CALL_LOG="$WORK_DIR/queue-call.log"

rm -rf "$WORK_DIR"
mkdir -p "$FIXTURE_DIR"
cp "$SCRIPT_DIR/pr-merge.sh" "$FIXTURE_DIR/pr-merge.sh"
cp "$SCRIPT_DIR/detect-platform.sh" "$FIXTURE_DIR/detect-platform.sh"

cat > "$FIXTURE_DIR/pr-metadata.sh" <<'SH'
#!/usr/bin/env bash
printf '%s\n' '{"baseRefName":"main","baseRepository":"mosaicstack/stack","headRefName":"fix/no-ci-fixture","headRefOid":"0123456789abcdef0123456789abcdef01234567","headRepository":"mosaicstack/stack"}'
SH

cat > "$FIXTURE_DIR/ci-queue-wait.sh" <<'SH'
#!/usr/bin/env bash
printf '%s\n' "$*" > "${MOSAIC_QUEUE_CALL_LOG:?}"
exit 42
SH
chmod +x "$FIXTURE_DIR"/*.sh

run_merge() {
    (
        cd "$WORK_DIR"
        export MOSAIC_QUEUE_CALL_LOG="$CALL_LOG"
        "$FIXTURE_DIR/pr-merge.sh" -n 123 "$@"
    ) >/dev/null 2>&1
}

fail=0

# With the flag: it must reach the guard invocation.
: > "$CALL_LOG"
set +e
run_merge --no-ci-expected
rc_with=$?
set -e
if [[ "$rc_with" -ne 42 ]]; then
    echo "FAIL(with): expected queue stub rc=42 to propagate, got $rc_with" >&2
    fail=1
elif ! grep -q -- '--no-ci-expected' "$CALL_LOG"; then
    echo "FAIL(with): --no-ci-expected did not reach the queue guard" >&2
    cat "$CALL_LOG" >&2
    fail=1
fi
# The rest of the guard invocation is unchanged by the flag.
for required in '--purpose merge' '-B fix/no-ci-fixture' '-R mosaicstack/stack' \
    '--sha 0123456789abcdef0123456789abcdef01234567'; do
    if ! grep -qF -- "$required" "$CALL_LOG"; then
        echo "FAIL(with): guard invocation lost '$required'" >&2
        cat "$CALL_LOG" >&2
        fail=1
    fi
done

# Without the flag: it must NOT appear in the guard invocation.
: > "$CALL_LOG"
set +e
run_merge
rc_without=$?
set -e
if [[ "$rc_without" -ne 42 ]]; then
    echo "FAIL(without): expected queue stub rc=42 to propagate, got $rc_without" >&2
    fail=1
elif grep -q -- '--no-ci-expected' "$CALL_LOG"; then
    echo "FAIL(without): --no-ci-expected reached the guard without being requested" >&2
    cat "$CALL_LOG" >&2
    fail=1
fi

if [[ "$fail" -eq 0 ]]; then
    echo "pr-merge no-ci-expected pass-through regression passed"
fi
exit "$fail"
