#!/usr/bin/env bash
# Run on the server after: git pull
# Usage: bash deploy/post-deploy.sh

set -euo pipefail

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

echo "==> Deploying cheraghbot from $ROOT"

if [[ ! -f .env ]]; then
    echo "ERROR: .env not found. Copy .env.example to .env and configure it first."
    exit 1
fi

echo "==> Composer install"
composer install --no-dev --optimize-autoloader --no-interaction

if command -v npm >/dev/null 2>&1 && [[ -f package.json ]]; then
    echo "==> Frontend build"
    npm ci --no-audit --no-fund
    npm run build
else
    echo "==> Skipping npm build (npm not found or no package.json)"
fi

echo "==> Laravel optimize"
php artisan storage:link 2>/dev/null || true
php artisan migrate --force
php artisan optimize:clear
php artisan config:cache
php artisan route:cache
php artisan view:cache

echo "==> Restart queue workers"
php artisan queue:restart

echo "==> Health check"
php artisan system:doctor

echo "==> Deploy finished."
