name: Deploy EternalAI

on:
  push:
    branches:
      - master
  workflow_dispatch:

jobs:
  deploy:
    runs-on: self-hosted
    steps:
      - name: Checkout code
        uses: actions/checkout@v4
        with:
          fetch-depth: 0

      - name: Setup Node.js
        uses: actions/setup-node@v4
        with:
          node-version: '20'

      - name: Install dependencies
        run: npm install

      - name: Generate Prisma Client
        run: npx prisma generate

      - name: Push database schema
        run: npx prisma db push
        env:
          DATABASE_URL: ${{ secrets.DATABASE_URL }}

      - name: Create logs directory
        run: mkdir -p logs

      - name: Restart PM2 process
        run: |
          if pm2 describe eternalai &>/dev/null; then
            pm2 reload ecosystem.config.js --update-env
            echo "PM2 process reloaded"
          else
            pm2 start ecosystem.config.js
            echo "PM2 process started"
          fi
          pm2 save

      - name: Health check
        run: |
          sleep 3
          for i in $(seq 1 15); do
            HTTP_CODE=$(curl -s -o /dev/null -w "%{http_code}" http://localhost:3001 || echo "000")
            if [ "$HTTP_CODE" = "200" ]; then
              echo "Health check passed (HTTP $HTTP_CODE)"
              exit 0
            fi
            echo "Waiting for server... (attempt $i, HTTP $HTTP_CODE)"
            sleep 2
          done
          echo "Health check failed"
          pm2 logs eternalai --lines 30 --nostream
          exit 1

      - name: Reload Nginx
        run: sudo nginx -t && sudo nginx -s reload || echo "Nginx reload skipped"

      - name: Deploy summary
        run: |
          echo "============================================"
          echo " Deploy completed: $(git rev-parse --short HEAD)"
          echo " $(git log -1 --format='%s')"
          echo "============================================"
