name: Backend Test/Lint

on:
  workflow_call:

jobs:
  tests:
    runs-on: ubuntu-latest

    env:
      PRODUCTION: false

    strategy:
      fail-fast: true
      matrix:
        # Database ENV Variablse as Specified by Mealie
        Database: [sqlite, postgres]

    # Services
    services:
      postgres:
        image: postgres
        env:
          POSTGRES_USER: mealie
          POSTGRES_PASSWORD: mealie
          POSTGRES_DB: mealie
        options: --health-cmd pg_isready --health-interval 10s --health-timeout 5s --health-retries 5
        ports:
          - 5432:5432
    # Steps
    steps:
      - name: Check out repository
        uses: actions/checkout@v2

      - name: Set up python
        uses: actions/setup-python@v2
        with:
          python-version: "3.10"

      - name: Install Poetry
        uses: snok/install-poetry@v1
        with:
          virtualenvs-create: true
          virtualenvs-in-project: true

      - name: Load cached venv
        id: cached-poetry-dependencies
        uses: actions/cache@v3
        with:
          path: .venv
          key: venv-${{ runner.os }}-${{ hashFiles('**/poetry.lock') }}

      - name: Check venv cache
        id: cache-validate
        if: steps.cached-poetry-dependencies.outputs.cache-hit == 'true'
        run: |
          echo "import black;print('venv good?')" > test.py && poetry run python test.py && echo ::set-output name=cache-hit-success::true
          rm test.py
        continue-on-error: true

      - name: Install dependencies
        run: |
          sudo apt-get update
          sudo apt-get install libsasl2-dev libldap2-dev libssl-dev tesseract-ocr-all
          poetry install
          poetry add "psycopg2-binary==2.8.6"
        if: steps.cached-poetry-dependencies.outputs.cache-hit != 'true' || steps.cache-validate.outputs.cache-hit-success != 'true'

      - name: Formatting (Black)
        run: |
          poetry run black . --check

      - name: Lint (Flake8)
        run: |
          make backend-lint

      - name: Mypy Typecheck
        run: |
          make backend-typecheck

      - name: Pytest
        env:
          DB_ENGINE: ${{ matrix.Database }}
          POSTGRES_SERVER: localhost
        run: |
          make backend-test
