#!/bin/bash
# Test script - runs backend, frontend, and e2e tests

set -e

SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
ROOT_DIR="$(dirname "$SCRIPT_DIR")"

# Colors for output
RED='\033[0;31m'
GREEN='\033[0;32m'
YELLOW='\033[1;33m'
BLUE='\033[0;34m'
NC='\033[0m' # No Color

BACKEND_PID=""
FRONTEND_PID=""
TEST_EXIT_CODE=0

cleanup() {
    echo -e "\n${YELLOW}Cleaning up...${NC}"
    if [ -n "$FRONTEND_PID" ]; then
        kill $FRONTEND_PID 2>/dev/null || true
        wait $FRONTEND_PID 2>/dev/null || true
    fi
    if [ -n "$BACKEND_PID" ]; then
        kill $BACKEND_PID 2>/dev/null || true
        wait $BACKEND_PID 2>/dev/null || true
    fi
    # Remove test database
    rm -f "$ROOT_DIR/server/test-e2e.db"
    exit $TEST_EXIT_CODE
}

trap cleanup SIGINT SIGTERM EXIT

echo -e "${BLUE}=== Starting Spiceflow Test Environment ===${NC}\n"

# Clean up old test database
rm -f "$ROOT_DIR/server/test-e2e.db"

# Use different ports for e2e tests (matching playwright.config.ts)
E2E_BACKEND_PORT=3001
E2E_FRONTEND_PORT=5174

# Start backend with test database
echo -e "${GREEN}Starting backend server with test database...${NC}"
cd "$ROOT_DIR/server"
SPICEFLOW_DB="test-e2e.db" SPICEFLOW_PORT=$E2E_BACKEND_PORT clj -M:run &
BACKEND_PID=$!

# Wait for backend to be ready
echo -e "${YELLOW}Waiting for backend...${NC}"
until curl -s http://localhost:$E2E_BACKEND_PORT/api/health > /dev/null 2>&1; do
    sleep 1
done
echo -e "${GREEN}Backend ready on http://localhost:$E2E_BACKEND_PORT${NC}"

# Start frontend
echo -e "${GREEN}Starting frontend server...${NC}"
cd "$ROOT_DIR/client"
VITE_API_URL="http://localhost:$E2E_BACKEND_PORT" npm run dev -- --port $E2E_FRONTEND_PORT &
FRONTEND_PID=$!

# Wait for frontend to be ready
echo -e "${YELLOW}Waiting for frontend...${NC}"
until curl -sk https://localhost:$E2E_FRONTEND_PORT > /dev/null 2>&1; do
    sleep 1
done
echo -e "${GREEN}Frontend ready on https://localhost:$E2E_FRONTEND_PORT${NC}\n"

# Run e2e tests
echo -e "${BLUE}=== Running E2E Tests ===${NC}\n"
cd "$ROOT_DIR/e2e"

# Run playwright tests (skip global setup/teardown since we manage servers ourselves)
if SKIP_SERVER_SETUP=1 npx playwright test "$@"; then
    echo -e "\n${GREEN}=== All tests passed ===${NC}"
    TEST_EXIT_CODE=0
else
    echo -e "\n${RED}=== Some tests failed ===${NC}"
    TEST_EXIT_CODE=1
fi
