name: Deploy GSM

on:
  push:
    branches: [main]
    paths:
      - 'gsm-backend/**'
      - 'gsm-frontend/**'
  workflow_dispatch:

jobs:
  deploy:
    runs-on: ubuntu-latest
    steps:
      - name: Checkout
        uses: actions/checkout@v4

      - name: Setup Node.js
        uses: actions/setup-node@v4
        with:
          node-version: '20'

      - name: Install backend dependencies
        run: |
          cd gsm-backend
          npm ci --production

      - name: Install frontend dependencies and build
        run: |
          cd gsm-frontend
          npm ci
          npm run build

      - name: Deploy Backend
        uses: appleboy/scp-action@v0.1.7
        with:
          host: 192.168.2.30
          username: root
          key: ${{ secrets.SSH_DEPLOY_KEY }}
          source: "gsm-backend/"
          target: "/opt/gameserver-monitor/backend/"
          strip_components: 1
          overwrite: true

      - name: Deploy Frontend
        uses: appleboy/scp-action@v0.1.7
        with:
          host: 192.168.2.30
          username: root
          key: ${{ secrets.SSH_DEPLOY_KEY }}
          source: "gsm-frontend/dist/"
          target: "/opt/gameserver-monitor/frontend/dist/"
          strip_components: 2
          overwrite: true

      - name: Restart Services
        uses: appleboy/ssh-action@v1.0.3
        with:
          host: 192.168.2.30
          username: root
          key: ${{ secrets.SSH_DEPLOY_KEY }}
          script: |
            cd /opt/gameserver-monitor/backend

            # Restart or start PM2 process with correct cwd
            if pm2 list | grep -q gsm-backend; then
              pm2 restart gsm-backend --update-env
            else
              pm2 start server.js --name gsm-backend
              pm2 save
            fi

            echo "Deploy complete!"
