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

ROOT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")/.." && pwd)"
BACKEND_DIR="$ROOT_DIR/backend"
FRONTEND_DIR="$ROOT_DIR/frontend"

echo "==> Online Clinic installation bootstrap"

command -v php >/dev/null 2>&1 || { echo "PHP 8.3+ is required."; exit 1; }
command -v composer >/dev/null 2>&1 || { echo "Composer is required."; exit 1; }
command -v npm >/dev/null 2>&1 || { echo "Node.js and npm are required."; exit 1; }

cd "$BACKEND_DIR"

if [[ ! -f .env ]]; then
  echo "==> Creating backend/.env from .env.example"
  cp .env.example .env
fi

echo "==> Installing backend dependencies"
composer install --no-interaction --prefer-dist

if ! grep -q '^APP_KEY=base64:' .env; then
  echo "==> Generating APP_KEY"
  php artisan key:generate
fi

echo "==> Linking public storage"
php artisan storage:link || true

cd "$FRONTEND_DIR"
echo "==> Installing frontend dependencies"
npm install

if [[ ! -f .env ]]; then
  echo "==> Creating frontend/.env from .env.example"
  cp .env.example .env 2>/dev/null || true
fi

cd "$ROOT_DIR/mobile-app"
if [[ -f package.json ]]; then
  echo "==> Installing mobile-app dependencies"
  npm install || true
  if [[ ! -f .env ]] && [[ -f .env.example ]]; then
    cp .env.example .env
  fi
fi

echo "==> Building frontend for Apache / production"
cd "$FRONTEND_DIR"
npm run build

echo "==> Starting Laravel API (php artisan serve) in background"
bash "$ROOT_DIR/scripts/start-api.sh" || true

echo "==> Starting Vite dev server (npm run dev) in background"
bash "$ROOT_DIR/scripts/start-dev.sh" || true

echo "==> Installing login autostart (composer/npm update, build, API, dev server on reboot)"
bash "$ROOT_DIR/scripts/autostart/install-autostart.sh" || true

cat <<EOF

Bootstrap complete.

=== Next steps ===
1. Configure Apache — see scripts/apache/README.md
2. Verify:  scripts/apache/verify-apache.bat  (Windows) or curl /setup/
3. Open:     http://clinic-frontend.localdev/setup/

Laravel API: http://127.0.0.1:8000 (background)
             http://clinic-backend.localdev (Apache vhost)

If /setup is 404: set DocumentRoot to frontend/dist and restart Apache.
If API calls fail: set VITE_API_URL=http://clinic-backend.localdev/api in frontend/.env
                   then run: cd frontend && npm run build

Vite dev: http://localhost:5173/setup  (started in background)

Stop API:  bash scripts/stop-api.sh
Start API: bash scripts/start-api.sh
Stop dev:  bash scripts/stop-dev.sh
Start dev: bash scripts/start-dev.sh

Autostart: registered for login / reboot — see scripts/autostart/README.md
Uninstall: bash scripts/uninstall.sh

EOF
