#!/bin/bash
# ═══════════════════════════════════════════════════════════════════
# TheKetoBay — Zero-Downtime Update Script
# Usage: bash update.sh [--skip-build]
# ═══════════════════════════════════════════════════════════════════

set -e
GREEN='\033[0;32m'; YELLOW='\033[1;33m'; NC='\033[0m'
APP_DIR="/var/www/theketobay"
SKIP_BUILD=${1:-""}

echo -e "${GREEN}🥑 TheKetoBay — Updating...${NC}"
cd $APP_DIR

# 1. Pull latest code (if git repo)
if [ -d .git ]; then
  echo -e "${YELLOW}📥 Pulling latest code...${NC}"
  git pull origin main
fi

# 2. Install new dependencies
echo -e "${YELLOW}📦 Installing dependencies...${NC}"
npm install --quiet

# 3. Run any new DB migrations
echo -e "${YELLOW}🗄️  Running migrations...${NC}"
npx prisma migrate deploy --schema=packages/db/prisma/schema.prisma 2>/dev/null || \
  npx prisma db push --schema=packages/db/prisma/schema.prisma

# 4. Build (unless skipped)
if [ "$SKIP_BUILD" != "--skip-build" ]; then
  echo -e "${YELLOW}🔨 Building apps...${NC}"
  npm run build
fi

# 5. Rebuild & restart Docker services one by one (zero downtime)
echo -e "${YELLOW}🔄 Restarting services...${NC}"

# API first (backend)
docker compose -f infrastructure/docker-compose.yml up -d --build --no-deps api
sleep 5

# Web (frontend)
docker compose -f infrastructure/docker-compose.yml up -d --build --no-deps web
sleep 5

# Bot
docker compose -f infrastructure/docker-compose.yml up -d --build --no-deps bot

# Reload nginx (no downtime)
docker exec ketobay_nginx nginx -s reload 2>/dev/null || docker restart ketobay_nginx

echo ""
echo -e "${GREEN}✅ Update complete!${NC}"
echo "$(date '+%Y-%m-%d %H:%M:%S') — Update deployed" >> $APP_DIR/infrastructure/deploy.log

# Run health check
bash $APP_DIR/infrastructure/monitor.sh
