name: Build & Deploy Mintel Blog

on:
  push:
    branches: [main]

jobs:
  build-and-deploy:
    runs-on: docker

    steps:
      - name: 📋 Log Workflow Start
        run: |
          echo "🚀 Starting deployment for ${{ github.repository }} (${{ github.ref }})"
          echo "  • Commit: ${{ github.sha }}"
          echo "  • Timestamp: $(date -u +'%Y-%m-%d %H:%M:%S UTC')"

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

      - name: 🔐 Login to private registry
        run: |
          echo "🔐 Authenticating with registry.infra.mintel.me..."
          echo "${{ secrets.REGISTRY_PASS }}" | docker login registry.infra.mintel.me -u "${{ secrets.REGISTRY_USER }}" --password-stdin

      - name: 🏗️ Build Docker image
        run: |
          echo "🏗️ Building Docker image (linux/arm64)..."
          docker buildx build \
            --pull \
            --platform linux/arm64 \
            --build-arg NEXT_PUBLIC_ANALYTICS_PROVIDER="${{ secrets.NEXT_PUBLIC_ANALYTICS_PROVIDER }}" \
            --build-arg NEXT_PUBLIC_UMAMI_WEBSITE_ID="${{ secrets.NEXT_PUBLIC_UMAMI_WEBSITE_ID }}" \
            --build-arg NEXT_PUBLIC_UMAMI_HOST_URL="${{ secrets.NEXT_PUBLIC_UMAMI_HOST_URL }}" \
            --build-arg NEXT_PUBLIC_PLAUSIBLE_DOMAIN="${{ secrets.NEXT_PUBLIC_PLAUSIBLE_DOMAIN }}" \
            --build-arg NEXT_PUBLIC_PLAUSIBLE_SCRIPT_URL="${{ secrets.NEXT_PUBLIC_PLAUSIBLE_SCRIPT_URL }}" \
            --build-arg NEXT_PUBLIC_GLITCHTIP_DSN="${{ secrets.NEXT_PUBLIC_GLITCHTIP_DSN }}" \
            -t registry.infra.mintel.me/mintel/mintel.me:latest \
            --push -f docker/Dockerfile .

      - name: 🚀 Deploy to production server
        run: |
          echo "🚀 Deploying to alpha.mintel.me..."
          
          # Setup SSH
          mkdir -p ~/.ssh
          echo "${{ secrets.ALPHA_SSH_KEY }}" > ~/.ssh/id_ed25519
          chmod 600 ~/.ssh/id_ed25519
          ssh-keyscan -H alpha.mintel.me >> ~/.ssh/known_hosts 2>/dev/null
          
          # Create .env file content
          cat > /tmp/mintel.me.env << EOF
          # ============================================================================
          # Mintel Blog - Production Environment Configuration
          # ============================================================================
          # Auto-generated by CI/CD workflow
          # ============================================================================
          
          # Application
          NODE_ENV=production
          DOMAIN=mintel.me
          ADMIN_EMAIL=${{ secrets.ADMIN_EMAIL }}
          
          # Analytics
          NEXT_PUBLIC_ANALYTICS_PROVIDER=${{ secrets.NEXT_PUBLIC_ANALYTICS_PROVIDER }}
          NEXT_PUBLIC_UMAMI_WEBSITE_ID=${{ secrets.NEXT_PUBLIC_UMAMI_WEBSITE_ID }}
          NEXT_PUBLIC_UMAMI_HOST_URL=${{ secrets.NEXT_PUBLIC_UMAMI_HOST_URL }}
          NEXT_PUBLIC_PLAUSIBLE_DOMAIN=${{ secrets.NEXT_PUBLIC_PLAUSIBLE_DOMAIN }}
          NEXT_PUBLIC_PLAUSIBLE_SCRIPT_URL=${{ secrets.NEXT_PUBLIC_PLAUSIBLE_SCRIPT_URL }}
          
          # Error Tracking (GlitchTip/Sentry)
          NEXT_PUBLIC_GLITCHTIP_DSN=${{ secrets.NEXT_PUBLIC_GLITCHTIP_DSN }}
          
          # Redis
          REDIS_URL=redis://redis:6379
          
          EOF
          
          # Upload .env and deploy
          scp -o StrictHostKeyChecking=accept-new /tmp/mintel.me.env root@alpha.mintel.me:/home/deploy/sites/mintel.me/.env
          
          ssh -o StrictHostKeyChecking=accept-new root@alpha.mintel.me bash << EOF
          set -e
          cd /home/deploy/sites/mintel.me
          
          chmod 600 .env
          chown deploy:deploy .env
          
          echo "${{ secrets.REGISTRY_PASS }}" | docker login registry.infra.mintel.me -u "${{ secrets.REGISTRY_USER }}" --password-stdin
          docker pull registry.infra.mintel.me/mintel/mintel.me:latest
          
          docker-compose down
          
          echo "🚀 Starting containers..."
          docker-compose up -d
          
          echo "⏳ Giving the app a few seconds to warm up..."
          sleep 10
          
          echo "🔍 Checking container status..."
          docker-compose ps
          
          if ! docker-compose ps | grep -q "Up"; then
            echo "❌ Container failed to start"
            docker-compose logs --tail=100
            exit 1
          fi

          echo "✅ Deployment complete!"
          EOF
          
          rm -f /tmp/mintel.me.env

      - name: 📊 Workflow Summary
        if: always()
        run: |
          echo "📊 Status: ${{ job.status }}"
          echo "🎯 Target: alpha.mintel.me"

      - name: 🔔 Gotify Notification (Success)
        if: success()
        run: |
          echo "Sending success notification to Gotify..."
          curl -k -s -X POST "${{ secrets.GOTIFY_URL }}/message?token=${{ secrets.GOTIFY_TOKEN }}" \
            -F "title=✅ Deployment Success: ${{ github.repository }}" \
            -F "message=The deployment of ${{ github.repository }} (branch: ${{ github.ref }}) was successful.
            
            Commit: ${{ github.sha }}
            Actor: ${{ github.actor }}
            Run ID: ${{ github.run_id }}" \
            -F "priority=5"

      - name: 🔔 Gotify Notification (Failure)
        if: failure()
        run: |
          echo "Sending failure notification to Gotify..."
          curl -k -s -X POST "${{ secrets.GOTIFY_URL }}/message?token=${{ secrets.GOTIFY_TOKEN }}" \
            -F "title=❌ Deployment Failed: ${{ github.repository }}" \
            -F "message=The deployment of ${{ github.repository }} (branch: ${{ github.ref }}) failed!
            
            Commit: ${{ github.sha }}
            Actor: ${{ github.actor }}
            Run ID: ${{ github.run_id }}
            
            Please check the logs for details." \
            -F "priority=8"
