name: main

on:
  push:
    branches: ["main"]

jobs:
  build-and-push:
    name: Build and push to Aliyun ACR
    runs-on: ubuntu-latest
    steps:
      - name: Checkout code
        uses: https://gitee.com/zsqai/checkout@v4

      - name: Set up Docker Buildx
        uses: https://gitee.com/zsqai/setup-buildx-action@v3

      - name: Login to Aliyun Container Registry
        uses: https://gitee.com/zsqai/login-action@v3
        with:
          registry: ${{ vars.ALIYUN_REGISTRY }}
          username: ${{ vars.ALIYUN_USERNAME }}
          password: ${{ secrets.ALIYUN_PASSWORD }}

      - name: Build and push Docker image
        uses: https://gitee.com/zsqai/build-push-action@v5
        with:
          context: .
          push: true
          no-cache: true
          build-args: |
            BUILD_VERSION=${{ github.sha }}
            BUILD_TIME=${{ github.run_number }}
            CACHE_BUST=${{ github.run_id }}
          tags: |
            ${{ vars.ALIYUN_REGISTRY }}/${{ vars.ALIYUN_NAMESPACE }}/${{ vars.ALIYUN_REPO }}:latest
            ${{ vars.ALIYUN_REGISTRY }}/${{ vars.ALIYUN_NAMESPACE }}/${{ vars.ALIYUN_REPO }}:${{ github.sha }}

  deploy:
    name: Deploy to server
    runs-on: ubuntu-latest
    needs: build-and-push
    steps:
      - name: Deploy via SSH
        uses: https://gitee.com/zsqai/ssh-action@v1.0.3
        with:
          host: ${{ vars.HOST }}
          username: root
          password: ${{ secrets.MAIN_HOST_PASSWORD }}
          port: 22
          script: |
            # 登录阿里云镜像仓库
            docker login --username=${{ vars.ALIYUN_USERNAME }} --password=${{ secrets.ALIYUN_PASSWORD }} ${{ vars.ALIYUN_REGISTRY }}

            # 确保网络存在
            docker network inspect web-network >/dev/null 2>&1 || docker network create web-network

            # 停止并删除旧容器
            docker stop website-01 2>/dev/null || true
            docker rm website-01 2>/dev/null || true

            # 删除旧镜像
            docker rmi ${{ vars.ALIYUN_REGISTRY }}/${{ vars.ALIYUN_NAMESPACE }}/${{ vars.ALIYUN_REPO }}:latest 2>/dev/null || true

            # 拉取最新镜像
            docker pull ${{ vars.ALIYUN_REGISTRY }}/${{ vars.ALIYUN_NAMESPACE }}/${{ vars.ALIYUN_REPO }}:latest

            # 运行新容器（不映射端口到宿主机）
            docker run -d \
              --name website-01 \
              --restart always \
              --network web-network \
              -e NODE_OPTIONS="--max-old-space-size=4096" \
              -e NODE_ENV="production" \
              ${{ vars.ALIYUN_REGISTRY }}/${{ vars.ALIYUN_NAMESPACE }}/${{ vars.ALIYUN_REPO }}:latest

            # 将 NPM 容器也连接到同一网络（如果还没连接）
            docker network connect web-network nginx-proxy-manager 2>/dev/null || true

            # 等待启动
            sleep 3

            # 查看日志
            echo ""
            echo "=== Container Logs ==="
            docker logs website-01 --tail 20

            # 清理无用镜像
            docker image prune -f