# ============================================================================
# CI/CD Pipeline - Avanzato Tecnologia
# ============================================================================
# Este workflow automatiza o build e deploy do site.
# 
# TRIGGER: Push na branch main ou manual (workflow_dispatch)
# ============================================================================

name: Build e Deploy

on:
  # Deploy automatico ao fazer push na main
  push:
    branches: [ main, master ]
  
  # Deploy manual pelo botao "Run workflow" no GitHub
  workflow_dispatch:
    inputs:
      environment:
        description: 'Ambiente'
        required: true
        default: 'production'
        type: choice
        options:
          - production
          - staging

  # Pull Request (apenas build, sem deploy)
  pull_request:
    branches: [ main, master ]

# Permissoes necessarias
permissions:
  contents: read

jobs:
  # ==========================================================================
  # JOB 1: Build
  # ==========================================================================
  build:
    name: Build
    runs-on: ubuntu-latest
    
    steps:
      # Passo 1: Checkout do codigo
      - name: Checkout codigo
        uses: actions/checkout@v4
      
      # Passo 2: Setup Node.js
      - name: Setup Node.js
        uses: actions/setup-node@v4
        with:
          node-version: '20'
          cache: 'npm'
      
      # Passo 3: Instalar dependencias
      - name: Instalar dependencias
        run: npm ci
      
      # Passo 4: Build
      - name: Build
        run: npm run build
      
      # Passo 5: Upload do artefato (para usar no job de deploy)
      - name: Upload artefato
        uses: actions/upload-artifact@v4
        with:
          name: dist
          path: dist/
          retention-days: 1

  # ==========================================================================
  # JOB 2: Deploy para Servidor (Producao)
  # ==========================================================================
  deploy-production:
    name: Deploy - Producao
    needs: build
    runs-on: ubuntu-latest
    # So executa na branch main/master ou manual com environment=production
    if: github.ref == 'refs/heads/main' || github.ref == 'refs/heads/master' || github.event.inputs.environment == 'production'
    
    steps:
      # Passo 1: Download do artefato buildado
      - name: Download artefato
        uses: actions/download-artifact@v4
        with:
          name: dist
          path: dist/
      
      # Passo 2: Preservar assets customizados (logo, imagens)
      - name: Preservar assets customizados
        run: |
          if [ -d "custom-assets" ]; then
            echo "Preservando assets customizados..."
            bash scripts/preserve-assets.sh dist/
          else
            echo "Nenhum asset customizado encontrado."
          fi
      
      # Passo 3: Deploy via SCP (SSH)
      - name: Deploy para servidor
        uses: appleboy/scp-action@v0.1.7
        with:
          host: ${{ secrets.SSH_HOST }}
          username: ${{ secrets.SSH_USER }}
          key: ${{ secrets.SSH_PRIVATE_KEY }}
          port: ${{ secrets.SSH_PORT || '22' }}
          source: "dist/*"
          target: ${{ secrets.DEPLOY_PATH || '/var/www/avanzato' }}
          strip_components: 1
          rm: true  # Remove arquivos antigos antes de copiar
      
      # Passo 4: Notificar (opcional - webhook Discord/Slack)
      - name: Notificar sucesso
        if: success()
        run: |
          echo "Deploy para producao concluido com sucesso!"
          echo "Site: https://avanzato.com.br"

  # ==========================================================================
  # JOB 3: Deploy para Staging (Opcional)
  # ==========================================================================
  deploy-staging:
    name: Deploy - Staging
    needs: build
    runs-on: ubuntu-latest
    # So executa em push para branch staging ou manual
    if: github.ref == 'refs/heads/staging' || github.event.inputs.environment == 'staging'
    
    steps:
      - name: Download artefato
        uses: actions/download-artifact@v4
        with:
          name: dist
          path: dist/
      
      - name: Deploy para staging
        uses: appleboy/scp-action@v0.1.7
        with:
          host: ${{ secrets.SSH_HOST }}
          username: ${{ secrets.SSH_USER }}
          key: ${{ secrets.SSH_PRIVATE_KEY }}
          port: ${{ secrets.SSH_PORT || '22' }}
          source: "dist/*"
          target: ${{ secrets.STAGING_PATH || '/var/www/avanzato-staging' }}
          strip_components: 1
          rm: true

  # ==========================================================================
  # JOB 4: Notificacao de Falha
  # ==========================================================================
  notify-failure:
    name: Notificar Falha
    needs: [build, deploy-production]
    runs-on: ubuntu-latest
    if: failure()
    
    steps:
      - name: Notificar falha
        run: |
          echo "ALERTA: O deploy falhou!"
          echo "Verifique os logs em: https://github.com/${{ github.repository }}/actions/runs/${{ github.run_id }}"
