#!/usr/bin/env bash
# Run Playwright end-to-end tests.
#
# Usage: ./scripts/test-e2e
#
# Starts the sis-server with a fresh database, runs the smoke test,
# then shuts down. Set SIS_URL to test against a running instance:
#   SIS_URL=http://localhost:8080 ./scripts/test-e2e
set -euo pipefail

PROJECT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")/.." && pwd)"
cd "$PROJECT_DIR"

# Build the server if needed
BIN="./.stack-work/dist/x86_64-linux/ghc-9.10.3/build/sis-server/sis-server"
if [ ! -f "$BIN" ]; then
    echo "[test-e2e] building server..."
    ./hs stack build --fast
fi

echo "[test-e2e] running Playwright tests..."

if [ -n "${SIS_URL:-}" ]; then
    npx playwright test --config=playwright.config.js "$@"
else
    DB_PATH="/tmp/sis-test-$$.db"
    PORT=8081

    # Kill anything already on our test port
    if lsof -ti:"$PORT" > /dev/null 2>&1; then
        echo "[test-e2e] killing existing process on port $PORT..."
        kill "$(lsof -ti:"$PORT")" 2>/dev/null || true
        sleep 1
    fi

    # Remove stale db
    rm -f "$DB_PATH"

    # Clean up on exit
    cleanup() {
        rm -f "$DB_PATH"
        if [ -n "${SERVER_PID:-}" ]; then
            kill "$SERVER_PID" 2>/dev/null
            wait "$SERVER_PID" 2>/dev/null || true
        fi
    }
    trap cleanup EXIT

    echo "[test-e2e] starting server on port $PORT with fresh db..."
    SIS_FRESH_DB=1 SIS_PORT="$PORT" "$BIN" --db "$DB_PATH" &
    SERVER_PID=$!

    # Wait for server to be ready
    echo "[test-e2e] waiting for server..."
    for i in $(seq 1 30); do
        if curl -sf http://localhost:$PORT/signup > /dev/null 2>&1; then
            echo "[test-e2e] server ready"
            break
        fi
        sleep 0.5
    done

    # Run tests
    SIS_URL="http://localhost:$PORT" npx playwright test --config=playwright.config.js "$@"
fi
