#!/usr/bin/env bash
# RM-03: pr-merge must guard the PR head branch, not its main base branch.

set -euo pipefail

SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
WORK_DIR="${MOSAIC_TEST_WORK_DIR:-$PWD/.mosaic-test-work/pr-merge-queue-branch}"
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/rm-03-fixture","headRefOid":"0123456789abcdef0123456789abcdef01234567","headRepository":"contributor/widgets-fork"}'
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

set +e
(
    cd "$WORK_DIR"
    export MOSAIC_QUEUE_CALL_LOG="$CALL_LOG"
    "$FIXTURE_DIR/pr-merge.sh" -n 123
) >/dev/null 2>&1
rc=$?
set -e

if [[ "$rc" -ne 42 ]]; then
    echo "FAIL: expected queue stub rc=42 to propagate, got $rc" >&2
    exit 1
fi
if [[ ! -s "$CALL_LOG" ]]; then
    echo "FAIL: merge wrapper did not invoke the queue guard" >&2
    exit 1
fi
if ! grep -q -- '-B fix/rm-03-fixture' "$CALL_LOG"; then
    echo "FAIL: merge queue guard did not receive PR head branch" >&2
    cat "$CALL_LOG" >&2
    exit 1
fi
if grep -q -- '-B main' "$CALL_LOG"; then
    echo "FAIL: merge queue guard still received the main base branch" >&2
    cat "$CALL_LOG" >&2
    exit 1
fi
if ! grep -q -- '-R mosaicstack/stack' "$CALL_LOG"; then
    echo "FAIL: merge queue guard did not receive the BASE repository for CI status" >&2
    cat "$CALL_LOG" >&2
    exit 1
fi
if grep -q -- '-R contributor/widgets-fork' "$CALL_LOG"; then
    echo "FAIL: merge queue guard received the fork head repository (B1: statuses are posted on the base repo)" >&2
    cat "$CALL_LOG" >&2
    exit 1
fi
if ! grep -q -- '--sha 0123456789abcdef0123456789abcdef01234567' "$CALL_LOG"; then
    echo "FAIL: merge queue guard did not receive the exact PR head SHA" >&2
    cat "$CALL_LOG" >&2
    exit 1
fi

echo "pr-merge queue branch/repository/SHA regression passed"
