#!/usr/bin/env bash
# Build and run the CIC shared Pascal test suite.
# Usage:
#   ./run_tests.sh              Run unit tests only (no broker needed)
#   ./run_tests.sh unit         Same as above
#   ./run_tests.sh integration  Start local broker, run integration tests, stop broker
#   ./run_tests.sh all          Start local broker, run all tests, stop broker
set -e

SCRIPT_DIR="$(cd "$(dirname "$0")" && pwd)"
LAZBUILD="C:/Prog/lazarus/32/lazarus/lazbuild.exe"
LPI="$SCRIPT_DIR/CICTests.lpi"
EXE="$SCRIPT_DIR/CICTests.exe"
MODE="${1:-unit}"
BROKER_STARTED=0

cleanup() {
  if [ "$BROKER_STARTED" -eq 1 ]; then
    echo ""
    echo "Stopping local MQTT broker..."
    bash "$SCRIPT_DIR/docker/stop_broker.sh"
  fi
}
trap cleanup EXIT

echo "=== Building test suite ==="
"$LAZBUILD" --build-all "$LPI" 2>&1 | tail -3

if [ ! -f "$EXE" ]; then
  echo "Build failed — $EXE not found."
  exit 1
fi

case "$MODE" in
  unit)
    echo ""
    echo "=== Running unit tests ==="
    "$EXE" --format=plain --suite=TMQTTPacketTests
    ;;
  integration)
    echo ""
    echo "=== Starting local MQTT broker ==="
    bash "$SCRIPT_DIR/docker/start_broker.sh"
    BROKER_STARTED=1
    echo ""
    echo "=== Running integration tests ==="
    "$EXE" --format=plain --suite=TMQTTIntegrationTests
    ;;
  all)
    echo ""
    echo "=== Starting local MQTT broker ==="
    bash "$SCRIPT_DIR/docker/start_broker.sh"
    BROKER_STARTED=1
    echo ""
    echo "=== Running all tests ==="
    "$EXE" --format=plain --all
    ;;
  *)
    echo "Usage: $0 [unit|integration|all]"
    exit 1
    ;;
esac

echo ""
echo "=== Done ==="
