#!/bin/bash
set -e

cd /var/lib/xiaoxia-saas-staging/repo/infra/docker

echo "🚀 开始部署小虾 SaaS..."

# 1. 拉取最新代码（CI/CD 已完成）
# 2. 构建镜像（CI/CD 已完成）

# 3. 滚动更新应用服务
echo "🔄 更新应用服务..."
docker compose up -d --no-deps api worker web

# 4. 健康检查
echo "⏳ 等待服务启动..."
for i in {1..30}; do
  if docker exec xiaoxia-api-staging wget -q --spider http://localhost:8000/health 2>/dev/null; then
    echo "✅ API 健康检查通过"
    break
  fi
  if [ $i -eq 30 ]; then
    echo "❌ 健康检查超时"
    echo "📋 API 日志："
    docker logs xiaoxia-api-staging --tail 50
    exit 1
  fi
  sleep 2
done

# 5. 清理旧镜像
echo "🧹 清理旧镜像..."
docker image prune -f

echo ""
echo "✅ 部署完成！"
echo ""
echo "📍 服务访问地址："
echo "   Web:  https://xiaoxiajianji.com"
echo "   API:  https://api.xiaoxiajianji.com/docs"
echo ""
echo "📊 容器状态："
docker compose ps
