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
        run: docker build -t iddaai-be:latest .

      - name: Eski Konteyneri Sil
        run: docker rm -f iddaai-be || true

      - name: Yeni Versiyonu 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: AI Engine Network Alias Garantile
        run: |
          AI_CONTAINER=$(docker ps --format '{{.Names}}' | grep iddaai-ai-engine | head -1)
          if [ -n "$AI_CONTAINER" ]; then
            docker network disconnect iddaai_iddaai-network $AI_CONTAINER 2>/dev/null || true
            docker network connect --alias iddaai-ai-engine iddaai_iddaai-network $AI_CONTAINER
            echo "AI engine alias eklendi: $AI_CONTAINER"
          else
            echo "AI engine container bulunamadi, alias atlanamadi"
          fi
