name: App Tests

on:
  pull_request:
    paths-ignore:
      - ".github/workflows/**"
  push:
    branches:
      - main
      - dev
  workflow_dispatch:

permissions:
  contents: read
  pull-requests: read

jobs:
  check-workflow-changes:
    runs-on: ubuntu-latest
    if: github.event_name == 'pull_request'
    steps:
      - name: Check for workflow modifications
        uses: dorny/paths-filter@v3
        id: changes
        with:
          filters: |
            workflows:
              - '.github/workflows/**'
      - name: Fail if workflows were modified
        if: steps.changes.outputs.workflows == 'true'
        run: |
          echo "::error::Workflow files were modified in this PR."
          exit 1

  test:
    needs: check-workflow-changes
    if: always()
    runs-on: ubuntu-latest
    strategy:
      max-parallel: 4
      matrix:
        python-version: ["3.12"]
    steps:
      - name: Check workflow verification result
        if: |
          github.event_name == 'pull_request_target' && 
          needs.check-workflow-changes.result == 'failure'
        run: exit 1

      - name: Checkout repository
        uses: actions/checkout@v4

      - name: Set up Python
        uses: actions/setup-python@v5
        with:
          python-version: ${{ matrix.python-version }}

      - name: Install Dependencies
        run: |
          python -m pip install --upgrade pip
          pip install -r requirements-dev.txt
          playwright install

      - name: Ruff
        run: |
          ruff check src

      - name: Set environment variables from secrets
        run: |
          if [ -n "${{ secrets.SECRET }}" ]; then echo "SECRET=${{ secrets.SECRET }}" >> $GITHUB_ENV; fi
          if [ -n "${{ secrets.TMDB_API }}" ]; then echo "TMDB_API=${{ secrets.TMDB_API }}" >> $GITHUB_ENV; fi
          if [ -n "${{ secrets.MAL_API }}" ]; then echo "MAL_API=${{ secrets.MAL_API }}" >> $GITHUB_ENV; fi
          if [ -n "${{ secrets.IGDB_ID }}" ]; then echo "IGDB_ID=${{ secrets.IGDB_ID }}" >> $GITHUB_ENV; fi
          if [ -n "${{ secrets.IGDB_SECRET }}" ]; then echo "IGDB_SECRET=${{ secrets.IGDB_SECRET }}" >> $GITHUB_ENV; fi
          if [ -n "${{ secrets.HARDCOVER_API }}" ]; then echo "HARDCOVER_API=${{ secrets.HARDCOVER_API }}" >> $GITHUB_ENV; fi
          if [ -n "${{ secrets.COMICVINE_API }}" ]; then echo "COMICVINE_API=${{ secrets.COMICVINE_API }}" >> $GITHUB_ENV; fi

      - name: Run Tests
        run: |
          coverage run src/manage.py test app users integrations lists events --parallel

      - name: Build Coverage Report
        run: |
          coverage combine
          coverage report
          coverage xml

      - name: Upload coverage to Codecov
        uses: codecov/codecov-action@v5
        with:
          token: ${{ secrets.CODECOV_TOKEN }}
