#!/usr/bin/env bash
# ═══════════════════════════════════════════════════════════════════════
# PAC 一键部署脚本(staging / production 通用)
#
# 用法(在服务器上):
#   sudo -u pac bash /opt/pac/deploy/deploy.sh staging
#   sudo -u pac bash /opt/pac/deploy/deploy.sh production
#
# 前置准备(首次):
#   1. 服务器装 node 20+ / pnpm 9+ / docker / git
#   2. git clone <repo> /opt/pac
#   3. cp /opt/pac/apps/pac-service/.env.example /opt/pac/apps/pac-service/.env
#      → vim 改:NODE_ENV / DATABASE_URL / REDIS_URL / JWT_* / DW_* / DEEPSEEK_*
#      → chmod 600 .env
#   4. cp /opt/pac/apps/pac-web/.env.example /opt/pac/apps/pac-web/.env  (NEXT_PUBLIC_*)
#   5. docker run -d pac-postgres / pac-redis(或独立托管实例)
#   6. systemctl enable pac-service pac-web(systemd unit 见 deploy/systemd/)
#
# 部署流程:
#   git pull → install → build types → migrate deploy → build service+web → restart
#
# 安全:
#   - 不会跑 prisma migrate dev / reset(生产数据安全)
#   - 不会改 .env(只读)
#   - 失败任一步立刻停(set -e)
# ═══════════════════════════════════════════════════════════════════════
set -euo pipefail

ENV="${1:-}"
if [[ "$ENV" != "staging" && "$ENV" != "production" ]]; then
  echo "❌ 必须指定环境: bash $0 staging|production"
  exit 1
fi

# 锁:防并发部署
LOCK="/tmp/pac-deploy.lock"
if [[ -e "$LOCK" ]]; then
  echo "❌ 另一次部署正在跑(/tmp/pac-deploy.lock 存在)。如确定无并发,rm $LOCK 后重试"
  exit 1
fi
touch "$LOCK"
trap 'rm -f "$LOCK"' EXIT

REPO_DIR="${PAC_REPO_DIR:-/opt/pac}"
cd "$REPO_DIR"

echo "═══════════════════════════════════════════════════════════"
echo "▶ PAC 部署 — 环境: $ENV / repo: $REPO_DIR / $(date '+%F %T')"
echo "═══════════════════════════════════════════════════════════"

# ─── 1. git pull ───
echo "▶ 1/7 git pull"
BRANCH=$([[ "$ENV" == "production" ]] && echo "main" || echo "main")  # 都拉 main;后续可拆 staging 分支
git fetch --quiet
git checkout "$BRANCH"
BEFORE_HEAD=$(git rev-parse --short HEAD)
git pull --ff-only
AFTER_HEAD=$(git rev-parse --short HEAD)
echo "  $BEFORE_HEAD → $AFTER_HEAD"

# ─── 2. 依赖 ───
echo "▶ 2/7 pnpm install"
pnpm install --frozen-lockfile

# ─── 3. types 包 ───
echo "▶ 3/7 build @pac/types"
pnpm --filter @pac/types build

# ─── 4. DB migrations(只 deploy,不 reset)───
echo "▶ 4/7 prisma migrate deploy"
cd apps/pac-service
pnpm exec prisma generate
pnpm exec prisma migrate deploy
cd "$REPO_DIR"

# ─── 5. 编译后端 ───
echo "▶ 5/7 build @pac/service"
cd apps/pac-service
rm -f tsconfig.tsbuildinfo  # 防 incremental cache 不输出 dist
pnpm build
cd "$REPO_DIR"

# ─── 6. 编译前端(NEXT_PUBLIC_* 必须 build-time 嵌入,所以每个环境独立 build)───
echo "▶ 6/7 build @pac/web"
pnpm --filter @pac/web build

# ─── 7. 重启服务 ───
echo "▶ 7/7 restart services"
if command -v systemctl >/dev/null 2>&1; then
  sudo systemctl restart pac-service
  sudo systemctl restart pac-web
  sleep 3
  systemctl is-active pac-service && echo "  ✓ pac-service active"
  systemctl is-active pac-web     && echo "  ✓ pac-web active"
else
  # 兜底:pm2 / 裸 node
  echo "  ⚠️ 未装 systemctl,需要手动重启 pac-service / pac-web"
  exit 1
fi

echo
echo "═══════════════════════════════════════════════════════════"
echo "✓ 部署完成 — $AFTER_HEAD ($(date '+%F %T'))"
echo "═══════════════════════════════════════════════════════════"
echo "验证:"
echo "  curl http://localhost:3101/health"
echo "  打开 https://<your-domain>/plans"
