name: Deploy CV Server

on:
  push:
    branches:
      - main
  workflow_dispatch: #  Allow manual deployment from GitHub UI

jobs:
  deploy:
    name: Pull and Restart
    runs-on: ubuntu-latest

    steps:
      - name: Deploy to server
        uses: appleboy/ssh-action@v1.0.3
        env:
          SERVICE_NAME: ${{ secrets.SERVICE_NAME || 'cv' }}
          REPO_PATH: ${{ secrets.REPO_PATH || '/home/txeo/Git/yo/cv' }}
        with:
          host: ${{ secrets.SSH_HOST }}
          username: ${{ secrets.SSH_USER }}
          key: ${{ secrets.SSH_PRIVATE_KEY }}
          port: ${{ secrets.SSH_PORT || '22' }}
          envs: SERVICE_NAME,REPO_PATH
          script: |
            set -e

            echo "🚀 Deploying to server..."
            echo "📥 Pulling latest changes..."
            cd $REPO_PATH

            # Fix repository permissions (entire repo, not just .git)
            echo "🔧 Fixing repository permissions..."
            sudo chown -R $USER:$USER .

            # Stash any local changes before pulling
            if ! git diff-files --quiet || ! git diff-index --quiet --cached HEAD; then
              echo "💾 Stashing local changes..."
              git stash push -m "Auto-stash before deployment $(date +%Y%m%d-%H%M%S)"
            fi

            git pull origin main

            # Reapply stashed changes if any (optional - comment out if not needed)
            # if git stash list | grep -q "Auto-stash"; then
            #   echo "♻️  Reapplying stashed changes..."
            #   git stash pop || echo "⚠️  Could not reapply stash (conflicts?)"
            # fi

            echo "🔄 Restarting service..."
            sudo systemctl restart $SERVICE_NAME

            echo "⏳ Waiting for service to start..."
            sleep 3

            # Check service status
            if sudo systemctl is-active --quiet $SERVICE_NAME; then
              echo "✅ Service restarted successfully"
              sudo systemctl status $SERVICE_NAME --no-pager -l
            else
              echo "❌ Service failed to start"
              sudo journalctl -u $SERVICE_NAME -n 50 --no-pager
              exit 1
            fi

      - name: Verify deployment
        uses: appleboy/ssh-action@v1.0.3
        with:
          host: ${{ secrets.SSH_HOST }}
          username: ${{ secrets.SSH_USER }}
          key: ${{ secrets.SSH_PRIVATE_KEY }}
          port: ${{ secrets.SSH_PORT || '22' }}
          script: |
            echo "🔍 Verifying deployment..."
            echo "Testing health endpoint..."
            sleep 2
            if curl -f http://localhost:1999/health > /dev/null 2>&1; then
              echo "✅ Health check passed"
              curl http://localhost:1999/health
            else
              echo "❌ Health check failed"
              exit 1
            fi
            echo "✅ Deployment verification complete!"
