#!/usr/bin/env bash
#
# Déploie et démarre Pharma SaaS sur un serveur local (Linux / macOS).
#
# Usage :
#   ./deploy.sh            # installe + démarre
#   ./deploy.sh --stop     # arrête
#   ./deploy.sh --port 8080 --bind 0.0.0.0 --skip-build
#
set -euo pipefail

PORT=8000
BIND=127.0.0.1
STOP=0
SKIP_BUILD=0

while [[ $# -gt 0 ]]; do
    case "$1" in
        --stop) STOP=1; shift ;;
        --port) PORT="$2"; shift 2 ;;
        --bind) BIND="$2"; shift 2 ;;
        --skip-build) SKIP_BUILD=1; shift ;;
        *) echo "Option inconnue : $1"; exit 1 ;;
    esac
done

ROOT="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
cd "$ROOT"

PID_DIR="$ROOT/storage/app/run"
LOG_DIR="$ROOT/storage/logs"

mkdir -p "$PID_DIR" "$LOG_DIR" storage/backups storage/app/imports

if [[ -f "$PID_DIR/web.pid" ]]; then
    WPID=$(cat "$PID_DIR/web.pid" 2>/dev/null || true)
    [[ -n "${WPID:-}" ]] && kill "$WPID" 2>/dev/null || true
fi
if [[ -f "$PID_DIR/queue.pid" ]]; then
    QPID=$(cat "$PID_DIR/queue.pid" 2>/dev/null || true)
    [[ -n "${QPID:-}" ]] && kill "$QPID" 2>/dev/null || true
fi
if [[ -f "$PID_DIR/scheduler.pid" ]]; then
    SPID=$(cat "$PID_DIR/scheduler.pid" 2>/dev/null || true)
    [[ -n "${SPID:-}" ]] && kill "$SPID" 2>/dev/null || true
fi
rm -f "$PID_DIR"/*.pid

if [[ "$STOP" -eq 1 ]]; then
    echo "Serveur local arrêté."
    exit 0
fi

if [[ ! -f .env ]]; then
    cp .env.example .env
    echo ".env créé depuis .env.example — renseignez APP_KEY et DB_* puis relancez."
    exit 1
fi
if [[ ! -f vendor/autoload.php ]]; then
    echo "Dépendances PHP manquantes : composer install"
    exit 1
fi
# node_modules n'est requis que pour recompiler : l'archive livrée contient des
# assets déjà compilés dans public/build/, ce qui permet un déploiement PHP seul.
if [[ ! -d node_modules && ! -f public/build/manifest.json ]]; then
    echo "Dépendances JS manquantes et aucun asset pré-compilé : npm install"
    exit 1
fi

# Vérifier MySQL
DB_HOST=$(grep -E '^DB_HOST=' .env | cut -d= -f2- | tr -d '\r')
DB_PORT=$(grep -E '^DB_PORT=' .env | cut -d= -f2- | tr -d '\r')
if ! (echo > /dev/tcp/"$DB_HOST"/"$DB_PORT") 2>/dev/null; then
    echo "Base de données injoignable sur $DB_HOST:$DB_PORT — démarrez MySQL/MariaDB."
    exit 1
fi

echo "==> Application des migrations"
php artisan migrate --force

if [[ "$SKIP_BUILD" -eq 0 ]]; then
    echo "==> Compilation des assets front-end"
    if [[ -d node_modules ]]; then
        npm run build
    else
        echo "    node_modules absent — utilisation des assets pré-compilés (public/build)"
    fi
fi

echo "==> Lien symbolique du stockage public"
if [[ ! -e public/storage && ! -L public/storage ]]; then
    php artisan storage:link
fi

echo "==> Mise en cache"
php artisan config:cache
php artisan route:cache
php artisan view:cache

echo "==> Démarrage des services"
nohup php artisan serve --host="$BIND" --port="$PORT" > "$LOG_DIR/web.out.log" 2> "$LOG_DIR/web.err.log" &
echo $! > "$PID_DIR/web.pid"
nohup php artisan queue:work --tries=3 --timeout=120 --sleep=3 > "$LOG_DIR/queue.out.log" 2> "$LOG_DIR/queue.err.log" &
echo $! > "$PID_DIR/queue.pid"
nohup php artisan schedule:work > "$LOG_DIR/scheduler.out.log" 2> "$LOG_DIR/scheduler.err.log" &
echo $! > "$PID_DIR/scheduler.pid"

sleep 2
if curl -fsS "http://127.0.0.1:$PORT/" >/dev/null 2>&1; then
    echo "    OK  application accessible"
fi

APP_URL=$(grep -E '^APP_URL=' .env | cut -d= -f2- | tr -d '\r')
echo ""
echo "  Pharma SaaS est déployé sur le serveur local."
echo "  URL        : $APP_URL"
echo "  Connexion  : admin@pharma.test / password"
echo "  SaaS       : super@pharma.test / password"
echo "  Arrêt      : ./deploy.sh --stop"
echo ""
