#!/usr/bin/env bash
#
# Full dev stack for the Astara Product DB + Lead Capture apps.
#
#   product-db:  backend  http://localhost:8000
#                frontend http://localhost:5173 (Vite + Inertia SSR)
#   lead-capture: PWA     http://localhost:3000 (Vite dev)
#
# Usage: ./dev.sh
#   Ctrl+C stops every process (backend, both Vite dev servers).
#
# The backend runs on php -S (not `artisan serve`) because this repo lives on
# a CIFS mount where `artisan serve` does not propagate env overrides to its
# child process; memory is raised to 512M so the price-list PDF builds fit.

set -euo pipefail

ROOT="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
LEAD_CAPTURE="${ROOT}/../lead-capture"
PHP="${PHP:-/home/mati/.config/herd-lite/bin/php}"
BACKEND_PORT="${BACKEND_PORT:-8000}"
VITE_PORT="${VITE_PORT:-5173}"
LEAD_PORT="${LEAD_PORT:-3000}"

pids=()
cleanup() {
    echo
    echo "Stopping dev stack..."
    for pid in "${pids[@]:-}"; do
        kill "${pid}" 2>/dev/null || true
    done
    # Kill any vite children (npm run spawns node under sh -c).
    pkill -f "vite.*${ROOT}" 2>/dev/null || true
    pkill -f "vite.*${LEAD_CAPTURE}" 2>/dev/null || true
    exit 0
}
trap cleanup INT TERM EXIT

echo "Starting Product DB dev stack"
echo "  backend      -> http://localhost:${BACKEND_PORT}"
echo "  product-db   -> http://localhost:${VITE_PORT}"
echo "  lead-capture -> http://localhost:${LEAD_PORT}"
echo

# Backend.
"${PHP}" -d memory_limit=512M -S localhost:${BACKEND_PORT} -t "${ROOT}/public" &
pids+=($!)

# Product DB frontend (Vite + Inertia SSR).
(cd "${ROOT}" && npm run dev) &
pids+=($!)

# Lead Capture PWA.
(cd "${LEAD_CAPTURE}" && npm run dev) &
pids+=($!)

echo "All processes up. Press Ctrl+C to stop."
wait