name: Deploy Docusaurus

on:
  push:
    branches:
      - main

jobs:
  build-and-deploy:
    runs-on: docker
    container:
      image: node:20-bookworm
      volumes:
        - /opt/forgejo/sites/docs:/deploy/docs

    steps:
      - name: Checkout del codice
        uses: actions/checkout@v4

      - name: Cache Node Modules
        uses: actions/cache@v4
        with:
          path: node_modules
          key: npm-${{ hashFiles('package-lock.json') }}
          restore-keys: |
            npm-

      - name: Installazione Dipendenze
        run: |
          if [ -d "node_modules" ]; then
            echo "📦 Cache hit - dipendenze già presenti"
          else
            echo "📥 Cache miss - scarico dipendenze..."
          fi
          npm ci --prefer-offline

      - name: Build Docusaurus
        run: |
          export NODE_OPTIONS="--max-old-space-size=4096"
          echo "🔨 Avvio build..."
          npm run build
          echo "✅ Build completato!"
          echo "📊 Files generati: $(find build -type f | wc -l)"

      - name: Pubblica sul Server
        run: |
          TARGET_DIR="/deploy/docs"
          echo "🚀 Inizio deploy su $TARGET_DIR..."
          
          # Verifica esistenza directory
          if [ ! -d "$TARGET_DIR" ]; then
            echo "❌ ERRORE: $TARGET_DIR non esiste!"
            exit 1
          fi
          
          # Pulisce la cartella di destinazione
          echo "🧹 Pulizia directory..."
          rm -rf $TARGET_DIR/*
          
          # Copia i nuovi file
          echo "📋 Copia files..."
          cp -r build/* $TARGET_DIR/
          
          # Permessi per Nginx (UID 101)
          echo "🔐 Imposto permessi..."
          chown -R 101:101 $TARGET_DIR
          chmod -R 755 $TARGET_DIR
          
          echo "✅ Deploy completato!"

      - name: Notifica Deploy
        if: success()
        run: |
          echo "━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━"
          echo "✅ Sito deployato con successo!"
          echo "━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━"
          echo "🌐 URL: http://192.168.1.245:8080"
          echo "📦 Commit: ${{ github.sha }}"
          echo "👤 Author: ${{ github.actor }}"
          echo "📅 Data: $(date '+%Y-%m-%d %H:%M:%S')"
          echo "🔖 Branch: ${{ github.ref_name }}"
          echo "📊 Files totali: $(find /deploy/docs -type f | wc -l)"
          echo "💾 Dimensione: $(du -sh /deploy/docs | cut -f1)"
          echo "━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━"

      - name: Notifica Errore
        if: failure()
        run: |
          echo "━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━"
          echo "❌ Deploy FALLITO!"
          echo "━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━"
          echo "📦 Commit: ${{ github.sha }}"
          echo "👤 Author: ${{ github.actor }}"
          echo "📅 Data: $(date '+%Y-%m-%d %H:%M:%S')"
          echo "━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━"
