#!/bin/bash
set -euo pipefail

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

echo "==> Deploying A-Monster Guard from $APP_DIR"

if [ ! -f .env ]; then
    echo "ERROR: .env missing. Copy .env.example to .env and configure production values first."
    exit 1
fi

git pull origin main

PHP_BIN="${PHP_BIN:-php}"
COMPOSER_BIN="${COMPOSER_BIN:-composer}"

if command -v "$COMPOSER_BIN" >/dev/null 2>&1; then
    "$COMPOSER_BIN" install --no-dev --optimize-autoloader --no-interaction
else
    echo "WARN: composer not found in PATH. Upload vendor/ or install Composer on the server."
fi

if command -v npm >/dev/null 2>&1 && [ -f package.json ]; then
    npm ci
    npm run build
else
    echo "WARN: npm not found. Build assets locally and upload public/build/."
fi

"$PHP_BIN" artisan migrate --force
"$PHP_BIN" artisan storage:link 2>/dev/null || true
"$PHP_BIN" artisan config:cache
"$PHP_BIN" artisan route:cache
"$PHP_BIN" artisan view:cache

chmod -R 775 storage bootstrap/cache 2>/dev/null || true

echo "==> Deploy complete."
