name: Deploy to Plesk (Node.js hosting)
on:
  push:
    branches:
      - main

jobs:
  build-and-deploy:
    runs-on: ubuntu-latest

    steps:
      - name: Checkout repository
        uses: actions/checkout@v4

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

      - name: Install dependencies
        run: npm ci

      - name: Build project
        run: npm run build

      - name: Check build output
        run: ls -la ./dist

      - name: Deploy via FTP to Plesk
        run: |
          sudo apt-get update && sudo apt-get install -y lftp
          HOST=${{ secrets.FTP_HOST }}
          USER=${{ secrets.FTP_USER }}
          PASSWORD=${{ secrets.FTP_PASSWORD }}
          TARGET_DIR=${{ secrets.FTP_TARGET_DIR }}
          lftp -c "
          open -u $USER,$PASSWORD $HOST
          set ssl:verify-certificate no
          mirror -R --delete --verbose \
            --exclude-glob node_modules/ \
            --exclude-glob .git/ \
            --exclude-glob .astro/ \
            --exclude-glob public/content/ \
            ./dist $TARGET_DIR/dist
          mirror -R --verbose ./public $TARGET_DIR/public
          put -O $TARGET_DIR package.json
          put -O $TARGET_DIR package-lock.json
          "

      - name: Trigger Plesk restart
        if: success()
        run: |
          echo "::notice::Build uploadé. Redémarre l'application Node.js depuis Plesk pour appliquer."
