name: django-unit-tests

on:
  push:
    branches: [main]
  pull_request:
  workflow_dispatch:

defaults:
  run:
    working-directory: django/aiservice

permissions:
  contents: read
  pull-requests: read
  checks: read

jobs:
  # This job checks if the workflow should run based on file changes
  check-changes:
    runs-on: ubuntu-latest
    outputs:
      should-run: ${{ steps.filter.outputs.aiservice == 'true' || github.event_name == 'workflow_dispatch' }}
    steps:
      - uses: actions/checkout@v4
        with:
          fetch-depth: 0
      - uses: dorny/paths-filter@v3
        id: filter
        with:
          filters: |
            aiservice:
              - 'django/aiservice/**'
              - '.github/workflows/django-unit-tests.yaml'

  # This job always runs and succeeds, allowing PRs to be merged when paths don't match
  no-aiservice-changes:
    name: No aiservice changes detected
    needs: check-changes
    if: needs.check-changes.outputs.should-run != 'true'
    runs-on: ubuntu-latest
    defaults:
      run:
        working-directory: .
    steps:
      - name: Skip tests
        run: echo "Skipping django unit tests - no changes in django/aiservice/"

  unit-tests:
    needs: [check-changes]
    if: needs.check-changes.outputs.should-run == 'true'
    runs-on: ubuntu-latest

    env:
      SECRET_KEY: ${{ secrets.SECRET_KEY }}
      DATABASE_URL: ${{ secrets.DATABASE_URL }}
      AZURE_OPENAI_API_KEY: ${{ secrets.AZURE_OPENAI_API_KEY }}
      AZURE_OPENAI_ENDPOINT: ${{ secrets.AZURE_OPENAI_ENDPOINT }}
      OPENAI_API_VERSION: ${{ secrets.OPENAI_API_VERSION }}
      ANTHROPIC_FOUNDRY_API_KEY: ${{ secrets.ANTHROPIC_FOUNDRY_API_KEY }}
      ANTHROPIC_FOUNDRY_BASE_URL: ${{ secrets.ANTHROPIC_FOUNDRY_BASE_URL }}
    steps:
      - name: Checkout code
        uses: actions/checkout@v4
        with:
          fetch-depth: 0
          token: ${{ secrets.GITHUB_TOKEN }}

      - name: Install uv
        uses: astral-sh/setup-uv@v7
        with:
          python-version: "3.12"
      - name: Install project dependencies
        working-directory: ./django/aiservice
        run: uv sync

      - name: Django Unit tests
        working-directory: ./django/aiservice
        run: uv run pytest

  django-unit-tests-status:
    runs-on: ubuntu-latest
    needs: [check-changes, no-aiservice-changes, unit-tests]
    if: always()
    defaults:
      run:
        working-directory: .
    steps:
      - name: Check all job statuses
        run: |
          if [[ "${{ needs.unit-tests.result }}" == "success" ]] || \
             [[ "${{ needs.no-aiservice-changes.result }}" == "success" ]]; then
            echo "✓ Django unit tests workflow completed successfully"
            exit 0
          else
            echo "✗ Django unit tests workflow failed"
            exit 1
          fi