name: Deploy to OVH

on:
  push:
    branches:
      - main
  workflow_dispatch:

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

      - name: Setup Node.js
        uses: actions/setup-node@v3
        with:
          node-version: '18'
          cache: 'npm'

      - name: Install dependencies
        run: npm ci

      - name: Deploy to OVH
        uses: easingthemes/ssh-deploy@main
        env:
          SSH_PRIVATE_KEY: ${{ secrets.OVH_SSH_KEY }}
          REMOTE_HOST: ${{ secrets.OVH_HOST }}
          REMOTE_USER: ${{ secrets.OVH_USER }}
          TARGET: ${{ secrets.OVH_DEPLOY_PATH }}
          EXCLUDE: |
            /node_modules/
            /.git/
            /.github/
            /.env
            /data/

      - name: Start/Restart application
        uses: appleboy/ssh-action@master
        with:
          host: ${{ secrets.OVH_HOST }}
          username: ${{ secrets.OVH_USER }}
          key: ${{ secrets.OVH_SSH_KEY }}
          script: |
            cd ${{ secrets.OVH_DEPLOY_PATH }}
            npm ci --production
            pm2 restart discord-bot || pm2 start server.js --name "discord-bot"
            pm2 save

      - name: Notification
        if: always()
        run: |
          if [ "${{ job.status }}" == "success" ]; then
            echo "✅ Déploiement réussi sur OVH"
          else
            echo "❌ Erreur lors du déploiement"
          fi
