#!/usr/bin/env bash
#
# FC Foz Platform — start the app (macOS / Linux).
# Assumes ./install.sh has already run once. Brings the backend + database up in
# Docker, then starts the frontend dev server in the foreground.
#
set -euo pipefail

# Always run from the repository root (the directory of this script).
cd "$(dirname "$0")"

bold() { printf "\033[1m%s\033[0m\n" "$1"; }
info() { printf "  \033[36m➜\033[0m %s\n" "$1"; }
err()  { printf "  \033[31m✗\033[0m %s\n" "$1" >&2; }

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

SUDO=""
if [ "$(id -u)" -ne 0 ] && have sudo; then SUDO="sudo"; fi

# Resolve docker (with sudo if the daemon needs it) and the compose command.
DOCKER_SUDO=""
if ! docker info >/dev/null 2>&1; then
  if $SUDO docker info >/dev/null 2>&1; then
    DOCKER_SUDO="$SUDO"
  else
    err "Docker daemon not reachable. Start Docker (or run ./install.sh) and retry."
    exit 1
  fi
fi
if $DOCKER_SUDO docker compose version >/dev/null 2>&1; then
  COMPOSE="$DOCKER_SUDO docker compose"
elif have docker-compose; then
  COMPOSE="$DOCKER_SUDO docker-compose"
else
  err "Docker Compose not found. Run ./install.sh first."
  exit 1
fi

bold "Starting backend + database (Docker)"
$COMPOSE up -d
info "backend: http://localhost:4000   ·   MongoDB: localhost:27018"

if [ ! -d frontend/node_modules ]; then
  err "frontend dependencies missing — run ./install.sh first."
  exit 1
fi

echo
bold "Starting frontend (http://localhost:8080) — press Ctrl+C to stop"
cd frontend
npm run dev
