#!/bin/bash
set -e

MODE=${1:-production}

if [ "$MODE" = "staging" ]; then
  COMPOSE="docker-compose.staging.yml"
  BUILD_CMD="npm run build:staging"
else
  COMPOSE="docker-compose.yml"
  BUILD_CMD="npm run build:prod"
fi

echo "🚀 Aziros deploying... ($MODE)"
cd ~/aziros

# Git Pull
echo "→ Code aktualisieren..."
git pull origin main

# Composer
echo "→ Composer install..."
docker compose -f $COMPOSE exec -T app \
  composer install --no-dev --optimize-autoloader

# NPM Build
echo "→ Assets bauen..."
docker compose -f $COMPOSE exec -T app \
  npm install --silent
docker compose -f $COMPOSE exec -T app \
  $BUILD_CMD

# Migrations
echo "→ Migrationen..."
docker compose -f $COMPOSE exec -T app \
  php artisan migrate --force

# Cache leeren
echo "→ Cache leeren..."
docker compose -f $COMPOSE exec -T app \
  php artisan config:clear
docker compose -f $COMPOSE exec -T app \
  php artisan cache:clear
docker compose -f $COMPOSE exec -T app \
  php artisan view:clear
docker compose -f $COMPOSE exec -T app \
  php artisan route:clear

# Cache neu aufbauen
echo "→ Cache aufbauen..."
docker compose -f $COMPOSE exec -T app \
  php artisan config:cache
docker compose -f $COMPOSE exec -T app \
  php artisan route:cache
docker compose -f $COMPOSE exec -T app \
  php artisan view:cache

# Services neu starten
echo "→ Services neu starten..."
docker compose -f $COMPOSE restart \
  worker scheduler mail-worker reverb

echo "✅ Deploy fertig! ($MODE)"
