#!/bin/bash
set -e

echo "🚀 初始化小虾 SaaS 服务器..."

# 1. 创建 Docker 网络
echo "📡 创建 Docker 网络..."
docker network create xiaoxia-net 2>/dev/null || echo "   网络已存在，跳过"

# 2. 启动基础设施（Postgres + Redis）
echo "🗄️  启动基础设施（Postgres + Redis）..."
cd /var/lib/xiaoxia-saas-staging/repo/infra/docker
docker compose -f infra.yml up -d

# 3. 等待数据库就绪
echo "⏳ 等待数据库启动..."
for i in {1..30}; do
  if docker exec xiaoxia-postgres pg_isready -U xiaoxia > /dev/null 2>&1; then
    echo "✅ 数据库已就绪"
    break
  fi
  if [ $i -eq 30 ]; then
    echo "❌ 数据库启动超时"
    exit 1
  fi
  sleep 2
done

# 4. 初始化数据库扩展
echo "🔧 初始化数据库扩展..."
docker exec xiaoxia-postgres psql -U xiaoxia -d xiaoxia_saas -c "CREATE EXTENSION IF NOT EXISTS \"uuid-ossp\";" 2>/dev/null || true

# 5. 启动应用（API + Worker + Web）
echo "🚀 启动应用服务..."
docker compose up -d

# 6. 健康检查
echo "⏳ 等待应用启动..."
for i in {1..30}; do
  if docker exec xiaoxia-api-staging wget -q --spider http://localhost:8000/api/v1/health 2>/dev/null; then
    echo "✅ 应用已就绪"
    break
  fi
  if [ $i -eq 30 ]; then
    echo "⚠️  应用健康检查未通过，请手动检查日志"
    docker compose logs api
    exit 0
  fi
  sleep 2
done

echo ""
echo "🎉 初始化完成！"
echo ""
echo "📍 服务访问地址："
echo "   Web:  https://xiaoxiajianji.com"
echo "   API:  https://api.xiaoxiajianji.com/docs"
echo "   Git:  https://git.xiaoxiajianji.com"
echo ""
echo "📊 容器状态："
docker compose ps
