#!/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 update deployment"

cd "$BACKEND_DIR"

if [[ ! -f .env ]]; then
  echo "Missing backend/.env"
  exit 1
fi

echo "==> Enabling maintenance mode"
php artisan down || true

echo "==> Updating backend dependencies"
composer install --no-interaction --prefer-dist --optimize-autoloader --no-dev

echo "==> Running migrations"
php artisan migrate --force

echo "==> Refreshing caches"
php artisan config:cache
php artisan route:cache
php artisan view:cache

cd "$FRONTEND_DIR"
echo "==> Updating frontend dependencies"
npm ci

echo "==> Building frontend"
npm run build

cd "$BACKEND_DIR"
echo "==> Restarting queue workers (if any)"
php artisan queue:restart || true

echo "==> Disabling maintenance mode"
php artisan up

echo "Update deployment complete."
