name: Deploy to Ubuntu VPS

on:
  workflow_call:
    secrets:
      VPS_HOST:
        required: true
      VPS_USERNAME:
        required: true
      VPS_SSH_KEY:
        required: true
      APP_PATH:
        required: true

jobs:
  deploy:
    runs-on: ubuntu-latest

    steps:
      - name: Checkout source code
        uses: actions/checkout@v2

      - name: Deploy via SSH
        uses: appleboy/ssh-action@v1.0.0
        with:
          host: ${{ secrets.VPS_HOST }}
          username: ${{ secrets.VPS_USERNAME }}
          key: ${{ secrets.VPS_SSH_KEY }}
          script: |
            bash -l -c '
              set -e

              echo "🔧 Loading environment (nvm, pnpm, etc.)..."
              export NVM_DIR="$HOME/.nvm"
              [ -s "$NVM_DIR/nvm.sh" ] && . "$NVM_DIR/nvm.sh"

              export PNPM_HOME="$HOME/.local/share/pnpm"
              export PATH="$PNPM_HOME:$PATH"

              echo "📂 Entering app directory"
              cd ${{ secrets.APP_PATH }}

              echo "🔄 Pulling latest code"
              git pull origin main

              echo "📦 Installing dependencies"
              pnpm install

              echo "🔨 Building project"
              pnpm build

              echo "📁 Copying .env to dist/"
              cp .env dist/.env

              echo "🚀 Running or restarting app with PM2"
              if pm2 describe padel-be > /dev/null; then
                pm2 restart padel-be --update-env
              else
                pm2 start pnpm --name "padel-be" -- start
              fi

              pm2 save
            '
