name: Deploy Iddaai Backend

on:
  push:
    branches: [main]

jobs:
  build-and-deploy:
    runs-on: ubuntu-latest
    steps:
      - name: Kodu Cek
        uses: actions/checkout@v4

      - name: Docker Build (Backend)
        run: docker build -t iddaai-be:latest .

      - name: Docker Build (AI Engine)
        run: docker build -t iddaai-ai-engine:latest ./ai-engine

      - name: Eski Konteynerleri Sil
        run: |
          docker rm -f iddaai-be || true
          docker rm -f iddaai-ai-engine || true

      - name: AI Engine'i Baslat
        run: |
          docker run -d \
            --name iddaai-ai-engine \
            --restart unless-stopped \
            --network iddaai_iddaai-network \
            -e DATABASE_URL='${{ secrets.DATABASE_URL }}' \
            iddaai-ai-engine:latest

      - name: Backend'i Baslat
        run: |
          docker run -d \
            --name iddaai-be \
            --restart unless-stopped \
            --network iddaai_iddaai-network \
            -p 127.0.0.1:1810:3005 \
            -e NODE_ENV=production \
            -e DATABASE_URL='${{ secrets.DATABASE_URL }}' \
            -e REDIS_HOST='${{ secrets.REDIS_HOST }}' \
            -e REDIS_PORT='${{ secrets.REDIS_PORT }}' \
            -e REDIS_PASSWORD='${{ secrets.REDIS_PASSWORD }}' \
            -e AI_ENGINE_URL='http://iddaai-ai-engine:8000' \
            -e JWT_SECRET='${{ secrets.JWT_SECRET }}' \
            -e JWT_ACCESS_EXPIRATION='1d' \
            iddaai-be:latest /bin/sh -c "npx prisma migrate deploy && node dist/src/main.js"

      - name: Saglik Kontrolu
        run: |
          sleep 10
          echo "=== AI Engine logs ==="
          docker logs --tail 30 iddaai-ai-engine || true
          echo "=== Backend logs ==="
          docker logs --tail 30 iddaai-be || true
          echo "=== AI Engine health ==="
          docker exec iddaai-ai-engine python -c "import urllib.request; print(urllib.request.urlopen('http://127.0.0.1:8000/health').read().decode())" || echo "AI engine health check failed"