name: Auto Deploy to Server

on:
  push:
    branches:
      - main
  workflow_dispatch: # Permite ejecutar manualmente

jobs:
  deploy:
    runs-on: ubuntu-latest
    
    steps:
      - name: Checkout código
        uses: actions/checkout@v4
        with:
          fetch-depth: 0

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

      - name: Instalar dependencias
        run: npm ci

      - name: Build aplicación
        run: npm run build

      - name: Verificar build
        run: |
          if [ ! -d "dist" ]; then
            echo "❌ Error: dist no existe"
            exit 1
          fi
          if [ -z "$(ls -A dist)" ]; then
            echo "❌ Error: dist está vacío"
            exit 1
          fi
          echo "✅ Build verificado"

      - name: Desplegar en servidor
        uses: appleboy/ssh-action@v1.0.3
        with:
          host: ${{ secrets.SERVER_HOST }}
          username: ${{ secrets.SERVER_USER }}
          key: ${{ secrets.SERVER_SSH_KEY }}
          port: ${{ secrets.SERVER_PORT || 22 }}
          script: |
            cd ${{ secrets.APP_PATH }}
            ./deploy.sh --skip-git

      - name: Notificar resultado
        if: always()
        run: |
          if [ "${{ job.status }}" == "success" ]; then
            echo "✅ Deploy completado exitosamente"
          else
            echo "❌ Deploy falló"
          fi
