# .gitea/workflows/deploy.yml
name: Build and Deploy JobMaker

on:
  push:
    branches: [ main ]
  pull_request:
    branches: [ main ]

env:
  REGISTRY: registry.redecarneir.us
  IMAGE_NAME: jobmaker-website
  DEPLOY_HOST: 92.246.130.58
  DEPLOY_USER: root
  CONTAINER_NAME: jobmaker-web

jobs:
  build:
    runs-on: ubuntu-latest
    
    steps:
    - name: 📥 Checkout code
      uses: actions/checkout@v4

    - name: 🐳 Set up Docker Buildx
      uses: docker/setup-buildx-action@v3

    - name: 🏷️ Generate tags
      id: meta
      run: |
        echo "VERSION=v$(date +%Y%m%d)-${GITHUB_SHA::8}" >> $GITHUB_OUTPUT
        echo "LATEST_TAG=${REGISTRY}/${IMAGE_NAME}:latest" >> $GITHUB_OUTPUT
        echo "VERSION_TAG=${REGISTRY}/${IMAGE_NAME}:v$(date +%Y%m%d)-${GITHUB_SHA::8}" >> $GITHUB_OUTPUT

    - name: 🔨 Build Docker image
      run: |
        echo "🔨 Building Docker image..."
        docker build \
          -t ${{ steps.meta.outputs.LATEST_TAG }} \
          -t ${{ steps.meta.outputs.VERSION_TAG }} \
          .

    - name: 🧪 Test container
      run: |
        echo "🧪 Testing container..."
        
        # Verificar se porta 8083 está livre
        echo "🔍 Checking port 8083..."
        if ss -tulpn | grep :8083; then
          echo "⚠️ Port 8083 is in use, stopping conflicting containers..."
          docker ps --filter "publish=8083" -q | xargs -r docker stop
          docker ps -a --filter "publish=8083" -q | xargs -r docker rm
          sleep 2
        fi
        
        # Usar nome único
        CONTAINER_NAME="test-container-$(date +%s)"
        echo "🚀 Starting test container: $CONTAINER_NAME on port 8083"
        
        # Iniciar container de teste
        docker run -d --name $CONTAINER_NAME -p 8083:80 ${{ steps.meta.outputs.LATEST_TAG }}
        
        # Aguardar inicialização
        echo "⏳ Waiting for container..."
        sleep 15
        
        # Verificar se container está rodando
        if ! docker ps | grep $CONTAINER_NAME; then
          echo "❌ Container not running"
          docker logs $CONTAINER_NAME 2>/dev/null || true
          docker stop $CONTAINER_NAME 2>/dev/null || true
          docker rm $CONTAINER_NAME 2>/dev/null || true
          exit 1
        fi
        
        # Teste interno
        echo "🔍 Testing nginx internally..."
        if docker exec $CONTAINER_NAME wget -q --spider http://localhost/; then
          echo "✅ Internal test passed"
        else
          echo "❌ Internal test failed"
          docker logs $CONTAINER_NAME
          docker stop $CONTAINER_NAME 2>/dev/null || true
          docker rm $CONTAINER_NAME 2>/dev/null || true
          exit 1
        fi
        
        # Teste externo
        echo "🔍 Testing external connectivity on port 8083..."
        if curl -f http://localhost:8083/ --max-time 10; then
          echo "✅ External test passed"
        else
          echo "⚠️ External test failed (but internal passed)"
        fi
        
        # Limpeza
        echo "🧹 Cleaning up test container..."
        docker stop $CONTAINER_NAME
        docker rm $CONTAINER_NAME
        
        echo "✅ Container tests passed!"

    - name: 📤 Push to registry
      run: |
        echo "📤 Pushing to registry..."
        docker push ${{ steps.meta.outputs.LATEST_TAG }}
        docker push ${{ steps.meta.outputs.VERSION_TAG }}
        echo "✅ Images pushed successfully!"

  deploy:
    needs: build
    runs-on: ubuntu-latest
    if: github.ref == 'refs/heads/main'
    
    steps:
    - name: 🔑 Setup SSH
      run: |
        mkdir -p ~/.ssh
        echo "${{ secrets.DEPLOY_SSH_KEY }}" > ~/.ssh/id_rsa
        chmod 600 ~/.ssh/id_rsa
        ssh-keyscan -H ${{ env.DEPLOY_HOST }} >> ~/.ssh/known_hosts

    - name: 🚀 Deploy to server
      run: |
        echo "🚀 Starting deployment..."
        
        ssh ${{ env.DEPLOY_USER }}@${{ env.DEPLOY_HOST }} << 'EOF'
          set -e
          
          echo "📥 Pulling latest image..."
          docker pull ${{ env.REGISTRY }}/${{ env.IMAGE_NAME }}:latest
          
          echo "🛑 Stopping current container..."
          docker stop ${{ env.CONTAINER_NAME }} || true
          docker rm ${{ env.CONTAINER_NAME }} || true
          
          echo "🚀 Starting new container on port 8083..."
          docker run -d \
            --name ${{ env.CONTAINER_NAME }} \
            --restart unless-stopped \
            -p 8083:80 \
            ${{ env.REGISTRY }}/${{ env.IMAGE_NAME }}:latest
          
          echo "🧪 Testing deployment..."
          sleep 5
          
          # Testar se está respondendo na porta 8083
          curl -f http://localhost:8083/ || exit 1
          
          echo "🧹 Cleaning up old images..."
          docker image prune -f
          
          echo "✅ Deployment completed successfully!"
        EOF

    - name: 📊 Deployment status
      run: |
        echo "📊 Checking deployment status..."
        
        ssh ${{ env.DEPLOY_USER }}@${{ env.DEPLOY_HOST }} << 'EOF'
          echo "=== Container Status ==="
          docker ps | grep ${{ env.CONTAINER_NAME }}
          
          echo "=== Container Logs (last 20 lines) ==="
          docker logs --tail 20 ${{ env.CONTAINER_NAME }}
          
          echo "=== Disk Usage ==="
          df -h
          
          echo "=== Docker Images ==="
          docker images | grep ${{ env.IMAGE_NAME }}
        EOF

  notify:
    needs: [build, deploy]
    runs-on: ubuntu-latest
    if: always()
    
    steps:
    - name: 📢 Notify deployment result
      run: |
        if [[ "${{ needs.deploy.result }}" == "success" ]]; then
          echo "🎉 Deployment successful!"
          echo "✅ JobMaker is live at: http://${{ env.DEPLOY_HOST }}"
          echo "✅ English version: http://${{ env.DEPLOY_HOST }}/en/"
        else
          echo "❌ Deployment failed!"
          echo "Check the logs above for details."
          exit 1
        fi

