name: Run unit tests

on:
  pull_request:
    branches:
      - "**"


jobs:
  test-docker:
    name: Tests (Docker)
    runs-on: ubuntu-latest

    services:
      postgres:
        image: postgres:15
        env:
          POSTGRES_USER: test
          POSTGRES_PASSWORD: test
          POSTGRES_DB: test
        ports:
          - 5432:5432
        options: >-
          --health-cmd pg_isready
          --health-interval 10s
          --health-timeout 5s
          --health-retries 5

    steps:
      - name: Checkout code
        uses: actions/checkout@v4

      - name: Build test image
        run: docker build -f Dockerfile.test -t model-test .

      - name: Initialise database schema
        run: |
          docker run --rm \
            --network host \
            -e DB_HOST=localhost \
            -e DB_NAME=test \
            -e DB_USERNAME=test \
            -e DB_PASSWORD=test \
            -e DB_PORT=5432 \
            model-test python scripts/init_db.py

      - name: Run tests
        run: |
          docker run --rm \
            --network host \
            -e EPC_AUTH_TOKEN=${{ secrets.DEV_EPC_AUTH_TOKEN }} \
            -e OPEN_EPC_API_TOKEN=${{ secrets.DEV_OPEN_EPC_API_TOKEN }} \
            -e HUBSPOT_API_KEY=${{ secrets.HUBSPOT_API_KEY }} \
            -e AWS_ACCESS_KEY_ID=${{ secrets.DEV_AWS_ACCESS_KEY_ID }} \
            -e AWS_SECRET_ACCESS_KEY=${{ secrets.DEV_AWS_SECRET_ACCESS_KEY }} \
            -e AWS_DEFAULT_REGION=${{ secrets.DEV_AWS_REGION }} \
            -e DB_HOST=localhost \
            -e DB_NAME=test \
            -e DB_USERNAME=test \
            -e DB_PASSWORD=test \
            -e DB_PORT=5432 \
            model-test pytest -vv -m 'not integration'

      # The DDD rewrite (tests/) defines SQLModel table classes that map to the
      # same physical tables as the legacy backend models. Both sets share the
      # one global SQLModel.metadata, so they cannot be imported into the same
      # pytest process. It runs as a separate invocation until the legacy
      # models are retired. Its DB is spawned in-process by pytest-postgresql,
      # so no DB service or env is required.
      - name: Run DDD tests
        run: |
          docker run --rm \
            --network host \
            model-test pytest -vv tests/
