name: Build and Deploy TenantUI

on:
  push:
    branches:
      - main

jobs:
  build-and-deploy:
    runs-on: host
    steps:
      - name: Checkout code
        run: |
          set -e
          cd /opt/deploy/tenantui || mkdir -p /opt/deploy/tenantui
          cd /opt/deploy/tenantui

          # 如果已有仓库就 pull，否则 clone
          if [ -d ".git" ]; then
            git fetch origin main
            git reset --hard origin/main
            git clean -fd
          else
            git clone --branch main ssh://git@git.laosankeji.com:2222/msumshk/TakeoutSaaS.TenantUI.git .
          fi

      - name: Build on host
        run: |
          set -e
          cd /opt/deploy/tenantui

          # 1. 保证 pnpm 可用（兼容没有 corepack 的 runner）
          if ! command -v pnpm >/dev/null 2>&1; then
            if command -v corepack >/dev/null 2>&1; then
              corepack enable
              corepack prepare pnpm@10.28.2 --activate
            elif command -v npm >/dev/null 2>&1; then
              npm install -g pnpm@10.28.2
            else
              echo "ERROR: corepack/npm 均不可用，请在 runner 安装 Node.js 20+"
              exit 1
            fi
          fi

          pnpm --version
          pnpm install --frozen-lockfile
          VITE_GLOB_API_URL=https://api-tenant-dev.laosankeji.com/api/tenant/v1 pnpm exec turbo run build --filter=@vben/web-antd...

          rm -rf publish/web-antd-dist
          mkdir -p publish
          cp -r apps/web-antd/dist publish/web-antd-dist

      - name: Build Docker image
        run: |
          set -e
          cd /opt/deploy/tenantui
          docker build -t takeoutsaas-tenantui:latest -f scripts/deploy/Dockerfile.runtime .

      - name: Deploy container
        run: |
          docker stop tenantui || true
          docker rm tenantui || true
          docker run -d \
            --name tenantui \
            --restart unless-stopped \
            -p 8010:8080 \
            takeoutsaas-tenantui:latest

      - name: Clean up old images
        run: |
          docker image prune -f
