name: Deploy

on:
  push:
    branches:
      - prod
      - test

env:
  NODE_ENV: production

jobs:
  deploy:
    runs-on: self-hosted
    container:
      image: catthehacker/ubuntu:act-latest
      options: --privileged
    steps:
      - name: Clone or update code
        run: |
          WORK_DIR="/workspace/rent-deploy"
          REPO_URL="https://gitea.pinzhuhui.com/xiaoquan/rent.git"

          echo "准备代码..."

          if [ -d "$WORK_DIR/.git" ]; then
            echo "代码目录已存在，更新代码..."
            cd $WORK_DIR
            git fetch origin
            git checkout ${{ github.ref_name }}
            git pull origin ${{ github.ref_name }}
          else
            echo "首次克隆代码..."
            git clone $REPO_URL $WORK_DIR
            cd $WORK_DIR
            git checkout ${{ github.ref_name }}
          fi

          echo "✅ 代码准备完成"
          echo "当前分支: $(git branch --show-current)"
          echo "最新提交: $(git log -1 --oneline)"

      - name: Deploy to test
        if: github.ref == 'refs/heads/test'
        run: |
          echo "部署到测试环境..."
          cd /workspace/rent-deploy/deploy/docker

          export TEST_DB_PASSWORD="${{ secrets.TEST_DB_PASSWORD }}"
          export TEST_JWT_SECRET="${{ secrets.TEST_JWT_SECRET }}"
          export ENCRYPTION_KEY="${{ secrets.ENCRYPTION_KEY }}"

          docker compose -f docker-compose.test.yml down --remove-orphans
          docker compose -f docker-compose.test.yml build --parallel
          docker compose -f docker-compose.test.yml up -d
          docker image prune -f

          echo "等待服务启动..."
          sleep 10
          docker compose -f docker-compose.test.yml ps
          echo "✅ 测试环境部署完成"

      - name: Deploy to production
        if: github.ref == 'refs/heads/prod'
        run: |
          echo "部署到生产环境..."
          cd /workspace/rent-deploy/deploy/docker

          export PROD_DB_PASSWORD="${{ secrets.PROD_DB_PASSWORD }}"
          export PROD_JWT_SECRET="${{ secrets.PROD_JWT_SECRET }}"
          export ENCRYPTION_KEY="${{ secrets.ENCRYPTION_KEY }}"

          docker compose -f docker-compose.prod.yml down --remove-orphans
          docker compose -f docker-compose.prod.yml build --parallel
          docker compose -f docker-compose.prod.yml up -d
          docker image prune -f

          echo "等待服务启动..."
          sleep 10
          docker compose -f docker-compose.prod.yml ps
          echo "✅ 生产环境部署完成"
