name: Run Backend tests

on:
  pull_request:
    paths:
      - 'agenta-backend/**'
      - 'docker-compose.yml'
      - 'docker-compose.*.yml'
  workflow_dispatch:
    inputs:
      debug:
        description: 'Run Docker logs step (true/false)'
        required: true
        default: 'false'

jobs:
  pytest:
    runs-on: ubuntu-latest
    steps:
      - uses: actions/checkout@v4

      - name: Set Environment Variables
        run: |
          echo "OPENAI_API_KEY=${{ secrets.NEXT_PUBLIC_OPENAI_API_KEY }}" >> $GITHUB_ENV

      - name: Install Curl
        run: sudo apt install curl -y

      - name: Start Docker Compose
        run: OPENAI_API_KEY=${{ secrets.NEXT_PUBLIC_OPENAI_API_KEY }} ENVIRONMENT=github docker compose -f "docker-compose.test.yml" up -d --build

      - name: Wait for Backend Service
        run: |
          sleep 10 && curl -i http://localhost/api/openapi.json

      - name: Restart Backend Service To Fetch Template Images
        run: docker container restart agenta-backend-test

      - name: Check Templates Exists
        run: |
          sleep 10 && curl -i http://localhost/api/containers/templates/

      - name: Run tests
        run: sleep 10 && docker exec agenta-backend-test pytest

      - name: Docker logs
        if: github.event_name == 'workflow_dispatch' && github.event.inputs.debug == 'true'
        run: docker ps -q | xargs -I {} docker logs {}
