#!/bin/bash
# CI script for makenotwork — replaces .build.yml (Sourcehut).
# Run on astra: /home/max/staging/run-ci.sh [filter]
#
# Runs: cargo check, cargo test --lib, cargo test --test integration,
#       cargo clippy, cargo audit (if installed).
#
# Usage:
#   ./run-ci.sh              # full CI
#   ./run-ci.sh auth         # only tests matching "auth"

set -euo pipefail

# Ensure ~/.cargo/bin is in PATH (SSH non-login shells may not source .profile)
export PATH="$HOME/.cargo/bin:$PATH"

SCRIPT_DIR="$(cd "$(dirname "$0")" && pwd)"
PROJECT_DIR="${SCRIPT_DIR}"

# Detect project directory layout
if [ -d "$SCRIPT_DIR/makenotwork/src" ]; then
    # Rsync'd staging layout (e.g., ~/staging/makenotwork/)
    PROJECT_DIR="$SCRIPT_DIR/makenotwork"
fi

cd "$PROJECT_DIR"

export DATABASE_URL="${DATABASE_URL:-postgres:///makenotwork_staging}"
export TEST_DATABASE_URL="${TEST_DATABASE_URL:-postgres:///postgres}"
export RUST_TEST_THREADS="${RUST_TEST_THREADS:-8}"
export CARGO_INCREMENTAL=0
export RUST_BACKTRACE=1

FILTER="${1:-}"
FAILURES=()
PASS=()

run_step() {
    local name="$1"
    shift
    echo ""
    echo "========================================"
    echo "  $name"
    echo "========================================"
    echo ""
    if "$@"; then
        PASS+=("$name")
    else
        FAILURES+=("$name")
        echo "FAILED: $name"
    fi
}

cleanup_test_dbs() {
    echo "Cleaning up orphaned test databases..."
    sudo -u postgres psql -Atc "SELECT datname FROM pg_database WHERE datname LIKE 'test_%';" 2>/dev/null | while read -r db; do
        sudo -u postgres psql -c "DROP DATABASE IF EXISTS \"$db\";" 2>/dev/null || true
    done
}

# Pre-cleanup
cleanup_test_dbs

# Step 1: Compilation check
run_step "cargo check" cargo check --features fast-tests

# Step 2: Unit tests
if [ -n "$FILTER" ]; then
    run_step "cargo test --lib ($FILTER)" cargo test --features fast-tests --lib "$FILTER"
else
    run_step "cargo test --lib" cargo test --features fast-tests --lib
fi

# Step 3: Integration tests
if [ -n "$FILTER" ]; then
    run_step "cargo test --test integration ($FILTER)" cargo test --features fast-tests --test integration "$FILTER" -- --test-threads=8
else
    run_step "cargo test --test integration" cargo test --features fast-tests --test integration -- --test-threads=8
fi

# Step 4: Clippy
run_step "cargo clippy" cargo clippy --features fast-tests --all-targets -- -D warnings

# Step 5: Security audit (optional)
if command -v cargo-audit &>/dev/null; then
    # Ignore known unfixable advisories:
    #   RUSTSEC-2023-0071: rsa via sqlx-mysql (MNW uses Postgres, not affected)
    run_step "cargo audit" cargo audit --ignore RUSTSEC-2023-0071
else
    echo ""
    echo "[skip] cargo-audit not installed (cargo install cargo-audit)"
fi

# Post-cleanup
cleanup_test_dbs

# Summary
echo ""
echo "========================================"
echo "  CI Summary"
echo "========================================"
echo ""

for step in "${PASS[@]}"; do
    echo "  PASS  $step"
done
for step in "${FAILURES[@]+"${FAILURES[@]}"}"; do
    echo "  FAIL  $step"
done

echo ""
if [ ${#FAILURES[@]} -eq 0 ]; then
    echo "All steps passed."
    exit 0
else
    echo "${#FAILURES[@]} step(s) failed."
    exit 1
fi
