name: CI - Test

on:
  workflow_call:
  workflow_dispatch:

jobs:
  test:
    runs-on: ubuntu-latest
    env:
      APT_CACHER_NG: http://192.168.88.14:3142
      DB_DRIVER: postgresql+psycopg2
      DB_HOST: 192.168.88.35
      DB_NAME: calminer_test
      DB_USER: calminer
      DB_PASSWORD: calminer_password
    services:
      postgres:
        image: postgres:17
        env:
          POSTGRES_USER: ${{ env.DB_USER }}
          POSTGRES_PASSWORD: ${{ env.DB_PASSWORD }}
          POSTGRES_DB: ${{ env.DB_NAME }}
        options: >-
          --health-cmd pg_isready
          --health-interval 10s
          --health-timeout 5s
          --health-retries 5
    steps:
      - name: Checkout repository
        uses: actions/checkout@v4

      - name: Set up Python
        uses: actions/setup-python@v4
        with:
          python-version: "3.12"

      - name: Configure apt proxy
        run: |
          if [ -n "${APT_CACHER_NG}" ]; then
            echo "Acquire::http::Proxy \"${APT_CACHER_NG}\";" | tee /etc/apt/apt.conf.d/01apt-cacher-ng
          fi

      - name: Install system packages
        run: |
          apt-get update
          apt-get install -y build-essential libpq-dev

      - name: Install dependencies
        run: |
          python -m pip install --upgrade pip
          pip install -r requirements.txt
          pip install -r requirements-test.txt

      - name: Run tests
        env:
          DATABASE_DRIVER: ${{ env.DB_DRIVER }}
          DATABASE_HOST: postgres
          DATABASE_PORT: 5432
          DATABASE_USER: ${{ env.DB_USER }}
          DATABASE_PASSWORD: ${{ env.DB_PASSWORD }}
          DATABASE_NAME: ${{ env.DB_NAME }}
        run: |
          pytest --cov=. --cov-report=term-missing --cov-report=xml --cov-fail-under=80 --junitxml=pytest-report.xml

      - name: Upload test artifacts
        if: always()
        uses: actions/upload-artifact@v3
        with:
          name: test-artifacts
          path: |
            coverage.xml
            pytest-report.xml
