#!/bin/bash
set -e

MODE=${1:-production}
SCRIPT_DIR="$(cd "$(dirname "$0")" && pwd)"
cd "$SCRIPT_DIR"

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)"

# Variablen für Docker Compose exportieren
set -a
source "$SCRIPT_DIR/src/.env"
set +a

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

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

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

# Verzeichnisse sicherstellen
docker compose -f $COMPOSE exec -T app \
  mkdir -p \
  bootstrap/cache \
  storage/framework/cache \
  storage/framework/sessions \
  storage/framework/views \
  storage/logs

docker compose -f $COMPOSE exec -T app \
  chmod -R 775 bootstrap/cache storage

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

# Translations
echo "→ Translations synchronisieren..."
docker compose -f $COMPOSE exec -T app \
  php artisan db:seed --class=TranslationSeeder --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)"
