name: Deploy to Staging

on:
  push:
    branches: [develop]
  workflow_dispatch:

jobs:
  deploy:
    runs-on: ubuntu-latest
    if: github.event_name == 'workflow_dispatch' || github.ref == 'refs/heads/develop'
    steps:
      - name: Deploy via SSH
        uses: appleboy/ssh-action@v1
        with:
          host: ${{ secrets.SSH_HOST }}
          port: ${{ secrets.SSH_PORT }}
          username: ${{ secrets.SSH_USER }}
          key: ${{ secrets.SSH_PRIVATE_KEY }}
          script_stop: true
          script: |
            REPO="${{ github.event.repository.name }}"
            DIR="$HOME/${REPO}"
            
            echo "=== Deploying ${REPO} to staging ==="
            cd "${DIR}" || { echo "Directory ${DIR} not found"; exit 1; }
            
            echo "--- Git pull ---"
            git pull origin develop
            
            echo "--- Install dependencies ---"
            pnpm install --frozen-lockfile
            
            echo "--- Build ---"
            pnpm build
            
            echo "--- Restart PM2 (if running) ---"
            pm2 describe "${REPO}" > /dev/null 2>&1 && pm2 restart "${REPO}" || echo "No PM2 process for ${REPO}"
            
            echo "=== Deploy complete ==="
