name: Deploy to Staging

on:
  push:
    branches: [develop]
  workflow_dispatch:
    inputs:
      skip_tests:
        description: 'Skip tests before deployment'
        required: false
        default: 'false'
        type: boolean

concurrency:
  group: staging-deployment
  cancel-in-progress: false

env:
  NODE_VERSION: '22'
  PNPM_VERSION: '9'
  STAGING_HOST: '37.24.237.181'
  STAGING_USER: 'payload'
  STAGING_PATH: '/home/payload/payload-cms'

jobs:
  # ===========================================================================
  # Pre-deployment checks (optional, can be skipped via workflow_dispatch)
  # ===========================================================================
  pre-checks:
    name: Pre-deployment Checks
    runs-on: ubuntu-latest
    if: ${{ github.event.inputs.skip_tests != 'true' }}
    steps:
      - name: Checkout code
        uses: actions/checkout@v4

      - name: Setup pnpm
        uses: pnpm/action-setup@v4
        with:
          version: ${{ env.PNPM_VERSION }}

      - name: Setup Node.js
        uses: actions/setup-node@v6
        with:
          node-version: ${{ env.NODE_VERSION }}
          cache: 'pnpm'

      - name: Install dependencies
        run: pnpm install --frozen-lockfile

      - name: Run ESLint
        run: pnpm lint

      - name: Run Unit Tests
        run: pnpm test:unit
        env:
          CSRF_SECRET: test-csrf-secret
          PAYLOAD_SECRET: test-payload-secret
          PAYLOAD_PUBLIC_SERVER_URL: https://test.example.com
          NEXT_PUBLIC_SERVER_URL: https://test.example.com
          EMAIL_DELIVERY_DISABLED: 'true'

  # ===========================================================================
  # Deploy to Staging Server
  # ===========================================================================
  deploy:
    name: Deploy to Staging
    runs-on: ubuntu-latest
    needs: [pre-checks]
    if: always() && (needs.pre-checks.result == 'success' || needs.pre-checks.result == 'skipped')
    steps:
      - name: Checkout code
        uses: actions/checkout@v4

      - name: Configure SSH
        run: |
          mkdir -p ~/.ssh
          echo "${{ secrets.STAGING_SSH_KEY }}" > ~/.ssh/staging_key
          chmod 600 ~/.ssh/staging_key
          cat >> ~/.ssh/config << EOF
          Host staging
            HostName ${{ env.STAGING_HOST }}
            Port 2222
            User ${{ env.STAGING_USER }}
            IdentityFile ~/.ssh/staging_key
            StrictHostKeyChecking no
            UserKnownHostsFile /dev/null
          EOF

      - name: Deploy to Staging
        run: |
          ssh staging << 'ENDSSH'
            set -e

            echo "=== Staging Deployment Started ==="
            echo "Time: $(date)"
            echo "Branch: ${{ github.ref_name }}"
            echo "Commit: ${{ github.sha }}"

            cd ${{ env.STAGING_PATH }}

            # Stash any local changes
            git stash --include-untracked || true

            # Fetch and checkout
            echo "=== Fetching latest code ==="
            git fetch origin develop
            git checkout develop
            git reset --hard origin/develop

            # Install dependencies
            echo "=== Installing dependencies ==="
            pnpm install --frozen-lockfile

            # Run migrations if any
            echo "=== Running migrations ==="
            pnpm payload migrate || echo "No migrations to run"

            # Build application
            echo "=== Building application ==="
            NODE_OPTIONS="--max-old-space-size=2048" pnpm build

            # Restart services
            echo "=== Restarting services ==="
            pm2 restart payload --update-env || pm2 start ecosystem.config.cjs --only payload
            pm2 restart queue-worker --update-env || pm2 start ecosystem.config.cjs --only queue-worker

            # Wait for service to be healthy
            echo "=== Waiting for service to start ==="
            sleep 10

            # Health check
            echo "=== Running health check ==="
            curl -sf http://localhost:3000/api/health || curl -sf http://localhost:3000/admin || echo "Health check endpoint not available"

            # Show status
            echo "=== Deployment Complete ==="
            pm2 status
            echo "Time: $(date)"
          ENDSSH

      - name: Verify Deployment
        run: |
          echo "Verifying staging deployment..."
          sleep 5

          # Check if staging is responding
          HTTP_STATUS=$(curl -s -o /dev/null -w "%{http_code}" https://pl.porwoll.tech/admin || echo "000")

          if [ "$HTTP_STATUS" -ge 200 ] && [ "$HTTP_STATUS" -lt 400 ]; then
            echo "Staging is responding with HTTP $HTTP_STATUS"
          else
            echo "Warning: Staging returned HTTP $HTTP_STATUS"
          fi

      - name: Create deployment summary
        if: always()
        run: |
          echo "## Staging Deployment Summary" >> $GITHUB_STEP_SUMMARY
          echo "" >> $GITHUB_STEP_SUMMARY
          echo "| Property | Value |" >> $GITHUB_STEP_SUMMARY
          echo "|----------|-------|" >> $GITHUB_STEP_SUMMARY
          echo "| Environment | Staging |" >> $GITHUB_STEP_SUMMARY
          echo "| URL | https://pl.porwoll.tech |" >> $GITHUB_STEP_SUMMARY
          echo "| Branch | ${{ github.ref_name }} |" >> $GITHUB_STEP_SUMMARY
          echo "| Commit | \`${{ github.sha }}\` |" >> $GITHUB_STEP_SUMMARY
          echo "| Triggered by | ${{ github.actor }} |" >> $GITHUB_STEP_SUMMARY
          echo "| Time | $(date -u '+%Y-%m-%d %H:%M:%S UTC') |" >> $GITHUB_STEP_SUMMARY

  # ===========================================================================
  # Notify on failure
  # ===========================================================================
  notify-failure:
    name: Notify on Failure
    runs-on: ubuntu-latest
    needs: [deploy]
    if: failure()
    steps:
      - name: Create failure summary
        run: |
          echo "## Staging Deployment Failed" >> $GITHUB_STEP_SUMMARY
          echo "" >> $GITHUB_STEP_SUMMARY
          echo "The deployment to staging failed. Please check the logs above for details." >> $GITHUB_STEP_SUMMARY
          echo "" >> $GITHUB_STEP_SUMMARY
          echo "**Branch:** ${{ github.ref_name }}" >> $GITHUB_STEP_SUMMARY
          echo "**Commit:** \`${{ github.sha }}\`" >> $GITHUB_STEP_SUMMARY
          echo "**Actor:** ${{ github.actor }}" >> $GITHUB_STEP_SUMMARY
