#!/usr/bin/env bash
set -euo pipefail

ROOT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")/.." && pwd)"
CLIENT_DIR="$ROOT_DIR/client"
SERVER_DIR="$ROOT_DIR/server"
SERVER_SCRIPTS_DIR="$SERVER_DIR/src/scripts"

usage() {
  cat <<'EOF'
Usage: ./scripts/common.sh <command>
Usage: ./scripts/common.sh script <script-name>

Commands:
  install   Install dependencies for client and server
  dev       Run client and server development servers together
  build     Build server and client
  start     Start server and client (production mode)
  lint      Run client lint checks
  seed      Seed backend data
  worker    Run backend worker
  scripts   List available server scripts from server/src/scripts
  script    Run a server script from server/src/scripts (with or without .ts)
EOF
}

if [[ $# -lt 1 ]]; then
  usage
  exit 1
fi

command_exists() {
  command -v "$1" >/dev/null 2>&1
}

if ! command_exists npm; then
  echo "npm is required but was not found in PATH."
  exit 1
fi

run_in_dir() {
  local dir="$1"
  shift
  (
    cd "$dir"
    "$@"
  )
}

list_server_scripts() {
  if [[ ! -d "$SERVER_SCRIPTS_DIR" ]]; then
    echo "Server scripts directory not found: $SERVER_SCRIPTS_DIR"
    exit 1
  fi

  find "$SERVER_SCRIPTS_DIR" -type f -name "*.ts" \
    ! -name "*.d.ts" \
    -printf "%P\n" | sort
}

run_server_script() {
  local input_name="$1"
  local script_name="$input_name"

  if [[ "$script_name" != *.ts ]]; then
    script_name="${script_name}.ts"
  fi

  local script_path="$SERVER_SCRIPTS_DIR/$script_name"
  if [[ ! -f "$script_path" ]]; then
    echo "Script not found: server/src/scripts/$script_name"
    echo "Use './scripts/common.sh scripts' to list available scripts."
    exit 1
  fi

  run_in_dir "$SERVER_DIR" npx ts-node "src/scripts/$script_name"
}

case "$1" in
  install)
    run_in_dir "$SERVER_DIR" npm install
    run_in_dir "$CLIENT_DIR" npm install
    ;;
  dev)
    trap 'kill 0' INT TERM EXIT
    (cd "$SERVER_DIR" && npm run dev) &
    (cd "$CLIENT_DIR" && npm run dev) &
    wait
    ;;
  build)
    run_in_dir "$SERVER_DIR" npm run build
    run_in_dir "$CLIENT_DIR" npm run build
    ;;
  start)
    trap 'kill 0' INT TERM EXIT
    (cd "$SERVER_DIR" && npm run start) &
    (cd "$CLIENT_DIR" && npm run start) &
    wait
    ;;
  lint)
    run_in_dir "$CLIENT_DIR" npm run lint
    ;;
  seed)
    run_in_dir "$SERVER_DIR" npm run seed
    ;;
  worker)
    run_in_dir "$SERVER_DIR" npm run worker
    ;;
  scripts)
    list_server_scripts
    ;;
  script)
    if [[ $# -lt 2 ]]; then
      echo "Please provide a script name. Example: ./scripts/common.sh script normalize-emails"
      exit 1
    fi
    run_server_script "$2"
    ;;
  *)
    usage
    exit 1
    ;;
esac
