#!/bin/bash
# Start the Workout Planner production server
# Usage: ./scripts/start.sh

SCRIPT_DIR="$(cd "$(dirname "$0")" && pwd)"
PROJECT_DIR="$(dirname "$SCRIPT_DIR")"
LOG_DIR="$PROJECT_DIR/logs"
PID_FILE="$PROJECT_DIR/.server.pid"

mkdir -p "$LOG_DIR"

# Check if already running
if [ -f "$PID_FILE" ]; then
  EXISTING_PID=$(cat "$PID_FILE")
  if kill -0 "$EXISTING_PID" 2>/dev/null; then
    echo "Server already running (PID $EXISTING_PID)"
    echo "http://localhost:3000"
    exit 0
  fi
  rm -f "$PID_FILE"
fi

cd "$PROJECT_DIR"

# Build if no .next directory exists
if [ ! -d ".next" ]; then
  echo "Building production bundle..."
  npm run build 2>&1 | tee "$LOG_DIR/build.log"
fi

# Start production server in background
echo "Starting server..."
NODE_ENV=production nohup npx next start -p 3000 \
  > "$LOG_DIR/server.log" 2>&1 &

echo $! > "$PID_FILE"
echo "Server started (PID $(cat "$PID_FILE"))"
echo "http://localhost:3000"
